JSON.parse()与JSON.stringify()

来源:互联网 发布:记账软件下载 编辑:程序博客网 时间:2024/06/05 17:38
JSON.parse() 方法用于将一个 JSON 字符串转换为对象。

例:

var text = '{ "sites" : [' +
'{ "name":"Runoob" , "url":"www.runoob.com" },' +
'{ "name":"Google" , "url":"www.google.com" },' +
'{ "name":"Taobao" , "url":"www.taobao.com" } ]}';


var obj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj.sites[1].name + " " +obj.sites[1].url;


结果:

  Google      www.google.com


JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。

例:

var str = {"name":"百度", "site":"http://www.baidu.com"}
str_pretty1 = JSON.stringify(str)
document.write( "只有一个参数情况:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty1 + "</pre>" );

document.write( "<br>" );
str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进
document.write( "使用参数情况:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty2 + "</pre>" ); // pre  用于格式化输出


结果:

只有一个参数情况:
{"name":"百度","site":"http://www.baidu.com"}

使用参数情况:
{
"name": "百度",
"site": "http://www.baidu.com"
}


0 0
原创粉丝点击