js中json对象和字符串的转换

JSON.parse() : 字符串-->json对象

1 var str = '{"name":"huangxiaojian","age":"23"}'//单引号写在{}外,每个属性名都必须用双引号,否则会抛出异常。
2 JSON.parse(str)
3 结果: 
4 Object
5 age: "23"
6 name: "huangxiaojian"
7 __proto__: Object

JSON.stringify() : json对象-->字符串

1 var a = {a:1,b:2}
2 JSON.stringify(a)
3 结果: 
4 "{"a":1,"b":2}"

例如:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset='UTF-8'>
 5 <title></title>
 6 </head>
 7 <body>
 8 </body>
 9 <script src="jquery.js"></script>
10 <script type="text/javascript">
11 console.log("字符串"+"--->"+"json对象");
12 var str1 = '{"name":"huangxiaojian","age":"23"}';//单引号写在{}外,每个属性名都必须用双引号,否则会抛出异常。
13 obj1=JSON.parse(str1);
14 console.log(str1+"--->");
15 console.log(obj1);
16 console.log("json对象"+"--->"+"字符串");
17 var obj2 = {a:1,b:2};
18 str2 = JSON.stringify(obj2);
19 console.log(obj2);
20 console.log('--->'+str2);
21 console.log("数组"+"--->"+"字符串");
22 var array = ["1","2"];
23 str3 = JSON.stringify(array);
24 console.log(array);
25 console.log('--->'+str3);
26 </script>
27 </html>

参考:https://www.cnblogs.com/seven7seven/p/4754465.html

posted @ 2019-03-23 21:26  清晨的第一抹阳光  阅读(459)  评论(0编辑  收藏  举报