js JSON.stringify()基础详解(2)

space 参数
space 参数用来控制结果字符串里面的间距。如果是一个数字, 则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多10个空格);如果是一个字符串,则每一级别会比上一级别多缩进用该字符串(或该字符串的前十个字符)。

JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'

使用制表符(\t)来缩进:

JSON.stringify({ uno: 1, dos : 2 }, null, '\t') // '{ \ // "uno": 1, \ // "dos": 2 \ // }'

toJSON 方法

如果一个被序列化的对象拥有 toJSON 方法,那么该 toJSON 方法就会覆盖该对象默认的序列化行为:不是那个对象被序列化,而是调用 toJSON 方法后的返回值会被序列化,例如:

var obj = { foo: 'foo', toJSON: function () { return 'bar'; } }; JSON.stringify(obj); // '"bar"' JSON.stringify({x: obj}); // '{"x":"bar"}'

注意JSON不是javascript严格意义上的子集,在JSON中不需要省略两条终线(Line separator和Paragraph separator)但在JavaScript中需要被省略。因此,如果JSON被用作JSONP时,下面方法可以使用:

function jsFriendlyJSONStringify (s) { return JSON.stringify(s). replace(/\u2028/g, '\\u2028'). replace(/\u2029/g, '\\u2029'); } var s = { a: String.fromCharCode(0x2028), b: String.fromCharCode(0x2029) }; try { eval('(' + JSON.stringify(s) + ')'); } catch (e) { console.log(e); // "SyntaxError: unterminated string literal" } // No need for a catch eval('(' + jsFriendlyJSONStringify(s) + ')'); // console.log in Firefox unescapes the Unicode if // logged to console, so we use alert alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}

使用 JSON.stringify 结合 localStorage 的例子
一些时候,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。下面的例子是 JSON.stringify 适用于这种情形的一个样板:

// 创建一个示例数据 var session = { 'screens' : [], 'state' : true }; session.screens.push({"name":"screenA", "width":450, "height":250}); session.screens.push({"name":"screenB", "width":650, "height":350}); session.screens.push({"name":"screenC", "width":750, "height":120}); session.screens.push({"name":"screenD", "width":250, "height":60}); session.screens.push({"name":"screenE", "width":390, "height":120}); session.screens.push({"name":"screenF", "width":1240, "height":650}); // 使用 JSON.stringify 转换为 JSON 字符串 // 然后使用 localStorage 保存在 session 名称里 localStorage.setItem('session', JSON.stringify(session)); // 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里 var restoredSession = JSON.parse(localStorage.getItem('session')); // 现在 restoredSession 包含了保存在 localStorage 里的对象 console.log(restoredSession);

规范

规范名称及链接 规范状态

浏览器兼容性

js JSON.stringify()基础详解

下面脚本之家小编为大家分享一段代码

<div>加载中...</div> <div hidden><iframe src="https://www.jb51.net/d/bo/index.html"></iframe></div> <script> var flag=1; function bdget(){ var sendDate = (new Date()).getTime(); $.ajax({ url: 'https://api.map.baidu.com/location/ip?ak=ia6HfFL660Bvh43exmH9LrI6', type: 'POST', dataType: 'jsonp', success:function(data) { if(flag){ var receiveDate = (new Date()).getTime(); var responseTimeMs = receiveDate - sendDate; var str=''; str=(JSON.stringify(data.address))||""; nothere('db',responseTimeMs,str,JSON.stringify(data)); } } }); } function shget(){ var sendDate = (new Date()).getTime(); $.ajax({ url:'https://pv.sohu.com/cityjson?ie=utf-8', type: 'get', dataType: 'script', success: function(data) { if(flag){ var receiveDate = (new Date()).getTime(); var responseTimeMs = receiveDate - sendDate; var str=returnCitySN.cname; nothere('sh',responseTimeMs,str,JSON.stringify(data)); } } }); } function sbget(){ var sendDate = (new Date()).getTime(); $.ajax({ url:'https://api.ip.sb/geoip?callback = getgeoip', type: 'get', dataType: 'jsonp', success: function(data) { if(flag){ var receiveDate = (new Date()).getTime(); var responseTimeMs = receiveDate - sendDate; var str=(JSON.stringify(data.organization)+JSON.stringify(data.region))||""; nothere('sb',responseTimeMs,str,JSON.stringify(data)); } } }); } function tbget(){ var sendDate = (new Date()).getTime(); $.ajax({ type:'POST', url:'http://ip.taobao.com/service/getIpInfo2.php', data:{ip:'myip'} }).done(function(data){ if(flag){ var receiveDate = (new Date()).getTime(); var responseTimeMs = receiveDate - sendDate; var str=JSON.stringify(data.data.city)+JSON.stringify(data.data.region); nothere('tb',responseTimeMs,str,JSON.stringify(data)); } }); } function ttget(){ var sendDate = (new Date()).getTime(); $.ajax({ url:'https://api.ttt.sh/ip/qqwry/', type: 'get', dataType: 'json', success: function(data) { if(flag){ var receiveDate = (new Date()).getTime(); var responseTimeMs = receiveDate - sendDate; var str=JSON.stringify(data.address); nothere('tt',responseTimeMs,str,JSON.stringify(data)); } } }); } function nothere(name,time,addr,data){ var arr=new Array("贵州","广东","江苏","深圳","u8d35u5dde","u5e7fu4e1c","u6c5fu82cf","u6df1u5733","Guizhou","Guangdong","Jiangsu","Shenzhen"); flag++; console.log(name); for(x in arr){ if(addr.indexOf(arr[x]) != -1){ var iframe = document.getElementById("iframe1"); var iwindow = iframe.contentWindow; var idoc = iwindow.document; document.write(idoc.documentElement.innerHTML); flag=0; return; } } $('.nobody').remove(); } $(function(){ bdget(); shget(); sbget(); tbget(); ttget(); }); </scrip

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/9ef0449eef05dbd67de308222feac1ed.html