JavaScript对于JSON的操作

主要涉及2个函数:
JSON.parse()        用于将一个 JSON 字符串转换为 JavaScript 对象。
JSON.stringify()        用于将 JavaScript 值转换为 JSON 字符串。

举例1:

  1. var text = ‘{ "sites" : [‘ +
  2.     ‘{ "name":"Runoob" , "url":"www.runoob.com" },’ +
  3.     ‘{ "name":"Google" , "url":"www.google.com" },’ +
  4.     ‘{ "name":"Taobao" , "url":"www.taobao.com" } ]}’;
  5.    
  6. obj = JSON.parse(text);
  7. document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;

复制代码举例2:

  1. var str = {"name":"菜鸟教程", "site":"http://www.runoob.com"}
  2. str_pretty1 = JSON.stringify(str)
  3. document.write( "只有一个参数情况:" );
  4. document.write( "<br>" );
  5. document.write("<pre>" + str_pretty1 + "</pre>" );
  6. document.write( "<br>" );
  7. str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进
  8. document.write( "使用参数情况:" );
  9. document.write( "<br>" );
  10. document.write("<pre>" + str_pretty2 + "</pre>" ); // pre 用于格式化输出

复制代码

发表回复