//转换
一个JSON数据类型的字付串,然后在JavaScript脚本中用eval()函数改变成JSON对象,就可以直接访问了。感觉这样比较方便,也更灵活一点。要注意的是要在返回的字符串两端加一对小括号:
var json1 = web_TreeView_TreeDemo.GetJson().value;
json1 = eval('(' + json1 + ')');
- 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);
- }
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); }
将字符串转 -> json 对象:
- //使用eval函数将字符串转化成json对象
- function myEval()
- {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = eval('(' + str + ')');
- alert(obj.toJSONString());
- }
//使用eval函数将字符串转化成json对象 function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = eval('(' + str + ')'); alert(obj.toJSONString()); }
- //使用 json.js 中的parseJSON方法
- function myEval2() {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = str.parseJSON();
- alert(obj.toJSONString());
//使用 json.js 中的parseJSON方法 function myEval2() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = str.parseJSON(); alert(obj.toJSONString());
将 json 对象 -> 字符串转 :
- function showCar() {
- var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");
- alert(carr.toJSONString());
- }
- function Car(make, model, year, color) {
- this.make = make;
- this.model = model;
- this.year = year;
- this.color = color;
- }
function showCar() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); alert(carr.toJSONString()); } function Car(make, model, year, color) { this.make = make; this.model = model; this.year = year; this.color = color; }
- function test()
- {
- var myJSONtext =
- {
- "bindings":
- [
- {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
- {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
- {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
- ]
- };
- var myObject = eval(myJSONtext);
- alert("对象长度:"+myObject.bindings.length);
- for(var i=0;i<myObject.bindings.length;i++){
- alert(myObject.bindings[i].method);
- }
- }