先创建一个html页面用来显示结果
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript" src="js/test5.js"></script> </head> <body> <button type="button" onclick="showJSON()">Click Me!</button> </body> </html>
/** test.js **/ function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[0].postcode); }
/** test1.js **/ function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[0].postcode); user.username = "Tom"; alert(user.username); }
/** test2.js **/ document.write("<script language='javascript' src='js/json2.js'></script>"); function showJSON() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); alert(JSON.stringify(carr)); } function Car(make, model, year, color){ this.make = make; this.model = model; this.year = year; this.color = color; }
/** test3.js **/ function showJSON() { var str = '{"id":"01","name":"Tom"}'; alert(JSON.stringify(JSON.parse(str))); }
/** test4.js **/ function showJSON() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = eval("(" + str + ")"); alert(JSON.stringify(obj)); }
/** test5.js **/ function showJSON() { var jsonObj2={persons:[{name:"jordan",sex:"m",age:"40"}, {name:"bryant",sex:"m",age:"28"}, {name:"McGrady",sex:"m",age:"27"} ]}; var person={name:"yaoMing",sex:"m",age:"26"}; jsonObj2.persons.push(person);//数组最后加一条记录 alert(JSON.stringify(jsonObj2)); jsonObj2.persons.pop();//删除最后一项 alert(JSON.stringify(jsonObj2)); jsonObj2.persons.shift();//删除第一项 alert(JSON.stringify(jsonObj2)); jsonObj2.persons.unshift(person);//数组最前面加一条记录 alert(JSON.stringify(jsonObj2)); jsonObj2.persons.splice(0,2);//开始位置,删除个数 alert(JSON.stringify(jsonObj2)); //替换不删除 var self={name:"tom",sex:"m",age:"24"}; var brother={name:"Mike",sex:"m",age:"29"}; jsonObj2.persons.splice(1,0,self,brother,self);//开始位置,删除个数,插入对象 alert(JSON.stringify(jsonObj2)); //替换并删除 jsonObj2.persons.splice(0,1,self,brother);//开始位置,删除个数,插入对象 alert(JSON.stringify(jsonObj2)); }
<span style="font-size:14px;">document.write("<script language='javascript' src='js/json2.js'></script>");//其中,这一句引入json2.js,这个我是去github下载的</span>像 JSON.stringify 这样的一些方法是 json2.js 中的,但是后来我发现不需要引入json2.js也能正常运行,所以我就对上面那句引入的代码有所怀疑是不是真的有效。大概现在的浏览器包含了json2.js支持里面的方法。至少chrome和360极速浏览器没问题,亲测过