json-study
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();

总结

JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation),是纯文本。
JSON 是 JS 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。
JSON 可以将 JavaScript对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从Web客户机传递给服务器端程序。

Author: 𝓣𝓪𝓭𝓶
Link: https://liuhongwei3.github.io/2019/09/24/json-study/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.