json学习笔记
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>json对象学习总结(runoob.com)</title>
</head>
<body>
<h2>来看看会是什么样的结果</h2>
<p id="demo"></p>
<script>
/*
json有两种方式:json对象和json数组,但这两种方式最外面都要用引号括起,所以都可以说都是字符串,当然这两种方式都可以嵌套.
json常用的方法:JSON.parse()是将json字符串或者json数组转换为js对象或js数组;
JSON.stringify()刚好反过来,是将js对象或js数组转换为json对象或json数组;
eval()方法和JSON.parse()方法差不多,也是将json字符串转换为js对象,用法是var obj = eval ("(" + myjson + ")");
*/
//JSON.parse()方法应用:
var myjson1 = '{ "one":"Google", "two":"Runoob", "three":"Taobao", "four":"Facebook" }';//json对象表示方法,需要注意的点是:都是要加引号的,不然就不是json对象
var myjson2 = '[ "Google", "Runoob", "Taobao", "Facebook" ]';//json数组表示方法,同样是需要加引号的
var obj1 = JSON.parse(myjson1);
obj1.one;//Google
var obj2 = JSON.parse(myjson2);
obj2[0];//Google
//JSON.stringify()方法应用:
var newarry1 = [ "Google", "Runoob", "Taobao", "Facebook" ];//js数组
var newobj2 = {one:"Google", two:"Runoob", three:"Taobao", four:"Facebook" };//js对象
newjson1 = JSON.stringify(newarry1);//["Google","Runoob","Taobao","Facebook"]
newjson2 = JSON.stringify(newobj2);//{"one":"Google","two":"Runoob","three":"Taobao","four":"Facebook"}
//eval()方法应用:
var txt = '{ "sites" : [' +
'{ "name":"菜鸟教程" , "url":"www.runoob.com" },' +
'{ "name":"google" , "url":"www.google.com" },' +
'{ "name":"微博" , "url":"www.weibo.com" } ]}';
var obj = eval ("(" + txt + ")");
var title = obj.sites[0].name;//菜鸟教程
</script>
</body>
</html>