JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
使用此功能的一个示例是Web服务响应.在"旧"时代,Web服务使用XML作为它们传回数据的主要数据格式,但是自从JSON出现(The JSON format is specified in 100 by Douglas Crockford)以来,它一直是首选格式,因为它更接近lightweight
你可以在官方JSON web site上找到更多信息.
JSON构建在两种 struct 之上:
- 名称/值对的集合.在各种语言中,这是作为对象、记录、 struct 、字典、哈希表、键控列表或关联数组实现的.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON struct
以下是一个JSON数据示例:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
JSON in JavaScript
JSON (in Javascript) is a string!
人们通常认为所有Javascript对象都是JSON,JSON是一个Javascript对象.这是不正确的.
In Javascript var x = {x:y}
is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'
. x
is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');
, x
is now an object but this is not JSON anymore.
See Javascript object Vs JSON
在使用JSON和JavaScript时,可能会try 使用eval
函数来计算回调中返回的结果,但不建议这样做,因为有两个字符(U+2028和U+2029)在JSON中有效,但在JavaScript中无效(请阅读本here中的更多内容).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
关于如何使用JSON解析器的示例(使用上述代码片段中的JSON):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON parser also offers another very useful method, stringify
. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse
and stringify
) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
顺便说一句,对于所有认为JSON只适用于JavaScript的人来说,请查看this post篇文章,它对此进行了解释并证实了这一点.
参考文献