JSON小结
程序员文章站
2022-05-23 13:01:42
...
JSON的全称就 JavaScript Object Notation (javascript对象表示法)
JSON是一种轻量级的,独立于语言的,自我描述的文本数据交换格式。JSON比XML更小,更快,更容易解析。
JSON的文件类型是 *.json, JSON文本的MIME类型是 appliction/json.
JSON的形式是一种对象和数组的混合形式,它的基础形式是 : key:value ,key的类型是 string.
JSON的数据可以以对象形式出现,也可以以数组形式出现。
基础形式(javascript中的无类型对象)
{ key: value } //也是最核心的形式
数组形式(将基础形式演变为数组,javascript中的数组对象)
var array = [obj, obj, obj] 或 var array = [ {key:value}, {key:value}, {key:value} ]
对象数组的高级形式
var people = { "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]} ;
(这种形式就是 key:value的形式,只不过value是一个对象数组)
我们来分解一下上面的形式:
var arrayobj = [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]; 即 var people = {"people" : arrayojb};
还有更高级的形式:
{ "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "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" } ] } 即: { "programmers": arrayObj , "authors": arrayObj, "musicians": arrayObj }
当然,我们的确是可以像操作数组对象那样来操作JSON数据的。
Javascript中的无类型对象
var book = { name: 'javascript book', title: 'javascript入门', author: 'ypzhao', introduce:function() { document.write('name = ' + name + ', title= ' + title); } };
Javascript中操作对象的属性和方法
操作属性 实例名.property 或 实例名[property] 实例名.method() 或 实例名[method]() 特别注意 使用eval()方法来解析JSON var dataObj=eval("("+data+")");//转换为json对象
仅代表个人见解,当然和官方的说法有些不同,但是其实质都是一样,那就是:
[Key : Value] / {Key : Value}