首页 > 语言 > JavaScript > 正文

npm qs模块使用详解

2024-05-06 15:44:15
字体:
来源:转载
供稿:网友

本文基本使用谷歌翻译加上自己的理解,权当加深记忆。

npm

简介

qs 是一个增加了一些安全性的查询字符串解析和序列化字符串的库。
主要维护者:Jordan Harband
最初创建者和维护者:TJ Holowaychuk

用法

var qs = require('qs');var assert = require('assert'); var obj = qs.parse('a=c');assert.deepEqual(obj, { a: 'c' }); var str = qs.stringify(obj);assert.equal(str, 'a=c');

解析对象

qs.parse(string, [options]);

qs 允许在查询字符串中使用[]的方式创建嵌套的对象。例如,字符串'foo[bar]=baz'可以转换为:

  assert.deepEqual(qs.parse('foo[bar]=baz'), {    foo: {      bar: 'baz'    }  });

When using the plainObjects option the parsed value is returned as a null object, created via Object.create(null) and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:

  var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });  assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } });

By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use plainObjects as mentioned above, or set allowPrototypes to true which will allow user input to overwrite those properties. WARNING It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.

  var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });  assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });

也可以解析 URI 编码:

  assert.deepEqual(qs.parse('a%5Bb%5D=c'), {    a: { b: 'c' }  });

还可以像这样嵌套对象:'foo[bar][baz]=foobarbaz':

  assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {    foo: {      bar: {        baz: 'foobarbaz'      }    }  });

当使用嵌套对象时,qs 在默认情况下最多解析到的深度是第五层(注:从第一个方括号到算起,到第五个方括号),例如尝试解析一个这样的字符串'a[b][c][d][e][f][g][h][i]=j'将会得到以下结果:

  var expected = {    a: {      b: {        c: {          d: {            e: {              f: {                '[g][h][i]': 'j'              }            }          }        }      }    }  };  var string = 'a[b][c][d][e][f][g][h][i]=j';  assert.deepEqual(qs.parse(string), expected);

可以给 qs.parse 传递一个 depth 参数覆盖默认值:

var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选