我查看了Wikipedia并对其进行了Google搜索,并阅读了官方文档,但我仍然没有真正了解JSON是什么以及为什么要使用它的意思。
我使用PHP,MySQL和Javascript / HTML构建应用程序已有一段时间了,如果JSON可以使我的生活更轻松,代码更好,用户界面更好,那么我想了解一下。有人可以给我一个简洁的解释吗?
JSON(JavaScript对象表示法)是一种轻量级格式,用于数据交换。它基于JavaScript语言的子集(使用JavaScript构建对象的方式)。如MDN中所述,某些JavaScript不是JSON,而某些JSON不是JavaScript。
使用此示例的一个例子是Web服务响应。在过去,Web服务使用XML作为传输回传数据的主要数据格式,但是自从JSON出现(JSON格式由Douglas Crockford在RFC 4627中指定)以来,它就成为首选格式,因为它具有更多的优势。轻巧的
JSON建立在两种结构上:
这是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(用Javascript)是一个字符串!
人们通常会假设所有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.
When working with JSON and JavaScript, you may be tempted to use the eval
function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this 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.
Example on how to use the JSON parser (with the json from the above code snippet):
//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}
上面的两个方法(parse
和stringify
)还带有第二个参数,该参数将在最终结果的每个级别上为每个键和值调用,并且每个值将由您输入的函数的结果替换。(更多关于这里)
顺便说一句,对于所有认为JSON仅适用于JavaScript的人,请查看这篇说明并以其他方式确认的文章。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句