Dojo库常用资源整理——dojo/json

dojo/json

Authors:Kris Zyp
Project owner:Kris Zyp
since:1.7.0

dojo/json is a module for JSON parsing and serialization based on the standard EcmaScript 5’s JSON object.

The module provides two functions, parse() and stringify().

Usage

parse()

The parse() function has a single required argument, the JSON string to be parsed, and an optional second argumentindicating if secure parsing should always be used. For example:

require(["dojo/json"], function(JSON){
  JSON.parse('{"hello":"world"}', true);
});

If the target platform supports native JSON parsing, dojo/json will always use the native parser (and serializer).

If no native parsing is available, dojo/json will use eval() to parse the JSON. When eval() is used, theparse() function’s second argument indicates if secure parsing should be used. Secure parsing will verify that theJSON is safe before evaluating it. Performing this verification is slower than directly evaluating, and secure parsingshould only be used if the JSON is from an unsecure source. The second argument has no effect on browsers with nativeparsing, since native parsing is always secure.

stringify()

The stringify() function takes a JavaScript value and serializes it to JSON. For example, to serialize an object wecould write:

require(["dojo/json"], function(JSON){
  var jsonString = JSON.stringify({ hello: "world" });
});

The stringify() function takes the same arguments as the standard JSON.stringify() function. This is explainedin more detail here: JSON.stringify()

The second argument is a replacer function, and the third argument allows you to provide a spacer string for prettyformatting.

Examples

Run Source Collapse

Converts a JSON string into a JavaScript object, modifies it and then outputs the JSON string again.

require(["dojo/json", "dojo/dom", "dojo/on", "dojo/domReady!"],
function(JSON, dom, on){
  on(dom.byId("convert"), "click", function(){
    var origin = '{"hello": "world"}';

    var obj = JSON.parse(origin);

    obj.hello = "Dojo";
    obj.something = "New";

    var output = JSON.stringify(obj);

    dom.byId("output").innerHTML = output;
  });
});
<button type="button" id="convert">Convert!</button>
<p><strong>Original JSON</strong></p>
<pre>{"hello": "world"}</pre>
<p><strong>Converted JSON</strong></p>
<pre id="output"></pre>

See Also



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值