JSON的两种结构------对象结构 & 数组结构
var jsonObj = { "键名1":值1, "键名2":值2, …… "键名n":值n }
var arr = [ { "键名1":值1, "键名2":值2 }, { "键名3":值3, "键名4":值4 }, …… ]
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }
Read------people.programmers[0].lastName; //McLaughlin Alter------people.musicians[1].lastName = "Rachmaninov"; delete------delete people.musicians[1].lastName;
for in 遍历: var myObj = { "name":"Tadm博客", "alexa":10000, "site":"https://liuhongwei3.github.io/" }; for (x in myObj) { $("#demo").html += x + "<br>"; } // name alexa site
for (x in myObj) { $("#demo").html += myObj[x] + "<br>"; } // Tadm博客 10000 https://liuhongwei3.github.io/
JSON.parse() 方法将数据转换为 JavaScript 对象: var obj = JSON.parse('{ "name":"Tadm博客", "alexa":10000, "site":"https://liuhongwei3.github.io/" }'); $("#demo").html = obj.name + ":" + obj.site; // Tadm博客:https://liuhongwei3.github.io/
JSON.stringify() 方法将 JavaScript 对象转换为字符串: var obj = JSON.stringify('{ "name":"Tadm博客", "alexa":10000, "site":"https://liuhongwei3.github.io/" }'); $("#demo").html = myJSON; // {"name":"Tadm博客","alexa":10000,"site":"https://liuhongwei3.github.io/"}
JAVA-JSON: JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); System.out.print(obj); // {"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
AJAX-JSON: xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; var jsonObj = JSON.parse(http_request.responseText); // jsonObj 变量现在包含数组结构,可以通过 jsonObj.name 和 jsonObj.country 的方式访问 document.getElementById("Name").innerHTML = jsonObj.name; document.getElementById("Country").innerHTML = jsonObj.country; } } xmlhttp.open("GET","/try/ajax/ajax_info.txt",true); xmlhttp.send();
|