Json笔记

Json语法

"param1":"value1", "param2":"value2", "param3":"value3"

var jsonObject = {
      "param1":"value1",
      "param2":"value2",
      "param3":"value3",
}

使用json标签编写的对象也具有属性和方法,能够利用据点标签进行访问:

alert(jsonObject.param1);

访问json数据

eval()
var myObject = eval ('(' + jsonObjectString + ')');
var user = '{"username" : "philb1234", "location" : "Spain", "height" : 1.8}';
var myObject = eval('(' + user + ')');
alert(myObject.username);

eval()函数会计算或运行作为参数传递的内容

 var x = eval(4*3);  //x=12

使用浏览器对JSON直接支持

JSON.parse():解释JSON字符串
var Mary = '{ "height" : 1.9, "age" : 36, "eyeColor": "brown"}';
var myObject = JSON.parse(Mary);
var out = " ";
for (i in myObject) {
      out += i + " = " + myObject[i] + "\n";
}
alert(out);
JSON.stringify():数据序列化
var Dan = new Object();
Dan.height = 1.85;
Dan.age = 41;
Dan.eyeColor = "blue";
alert(JSON.stringify("Dan"));

模拟关联数组

var conference = {"startDay" : "Monday",
      "nextDay" : "Tuesday",
      "endDay" : "Wednesday"
}
alert(conference["startDay"]);

在JavaScript里,object["property"]和object.property是相同的语法。

数组

属性值可以是数组:

var bookLisjtObject = {
      "booklist" : [ "Foundation", "Dune", "Eon", "2001 A Space Odyssey", "Stranger In A Stranger Land"]
}
var book = bookListObject.booklist[2];  // "Eon"

对象

var booklistObject = {
      "booklist" : [{"title" : "Foundation", "author" : "Isaac Asimov"},
            {"title" : "Dune", "author" : "Frank"},
            {"title" : "Eon", "author" : "Greg Bear"},
            {"title" : "2001 A Space Odyssey", "author" : "Arthur C. Clarke"}]
}
alert(booklistObject.booklist[2].author);

你可能感兴趣的