querystring.stringify(obj[, sep[, eq[, options]]])


  • obj <Object> 要序列化为网址查询字符串的对象
  • sep <string> 用于在查询字符串中分隔键值对的子字符串。 默认值: '&'
  • eq <string>用于在查询字符串中分隔键和值的子字符串。 默认值: '='
  • options
    • encodeURIComponent <Function> 当将网址不安全的字符转换为查询字符串中的百分比编码时使用的函数。 默认值: querystring.escape()

querystring.stringify() 方法通过遍历对象的"自有属性"从给定的 obj 生成网址查询字符串。

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// 返回 'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// 返回 'foo:bar;baz:qux'

默认情况下,查询字符串中需要百分比编码的字符将被编码为 UTF-8。 如果需要替代的编码,则需要指定替代的 encodeURIComponent 选项:

// 假设 gbkEncodeURIComponent 函数已存在,

querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
                      { encodeURIComponent: gbkEncodeURIComponent });
  • obj <Object> The object to serialize into a URL query string
  • sep <string> The substring used to delimit key and value pairs in the query string. Default: '&'.
  • eq <string>. The substring used to delimit keys and values in the query string. Default: '='.
  • options
    • encodeURIComponent <Function> The function to use when converting URL-unsafe characters to percent-encoding in the query string. Default: querystring.escape().

The querystring.stringify() method produces a URL query string from a given obj by iterating through the object's "own properties".

It serializes the following types of values passed in obj: <string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]> Any other input values will be coerced to empty strings.

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// Returns 'foo:bar;baz:qux'

By default, characters requiring percent-encoding within the query string will be encoded as UTF-8. If an alternative encoding is required, then an alternative encodeURIComponent option will need to be specified:

// Assuming gbkEncodeURIComponent function already exists,

querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
                      { encodeURIComponent: gbkEncodeURIComponent });