简体   繁体   中英

Encode client request params in Node.js

I need a method/implementation in Node.js that get a hash or array, and transform it to the HTML request param, just like jQuery.param()

var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
}; // => "a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3"

*I just cant use it from jQuery since it depends on Browser native implementations.

I don't know such native function or module but you can use this one:

// Query String able to use escaping
var query = require('querystring');

function toURL(object, prefix)
{
  var result = '',
    key = '',
    postfix = '&';

  for (var i in object)
  {
    // If not prefix like a[one]...
    if ( ! prefix)
    {
      key = query.escape(i);
    }
    else
    {
      key = prefix + '[' + query.escape(i) + ']';
    }

    // String pass as is...
    if (typeof(object[i]) == 'string')
    {
      result += key + '=' + query.escape(object[i]) + postfix;
      continue;
    }

    // objectects and arrays pass depper
    if (typeof(object[i]) == 'object' || typeof(object[i]) == 'array')
    {
      result += toURL(object[i], key) + postfix;
      continue;
    }

    // Other passed stringified
    if (object[i].toString)
    {
      result += key + '=' + query.escape(object[i].toString()) + postfix;
      continue;
    }
  }
  // Delete trailing delimiter (&) Yep it's pretty durty way but
  // there was an error gettin length of the objectect;
  result = result.substr(0, result.length - 1);
  return result;
}

// try
var x = {foo: {a:{xxx:9000},b:2}, '[ba]z': 'bob&jhonny'};
console.log(toURL(x));
// foo[a]=1&foo[b]=2&baz=bob%26jhonny

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM