If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);
(如果我使用var jSonString = JSON.stringify(testObject);
将上述对象转换为JSON var jSonString = JSON.stringify(testObject);
)
, what is the difference between the 2 (JS obj and JSON)?(,2(JS obj和JSON)有什么区别?)
JSON is a data interchange format.
(JSON是一种数据交换格式。)
It's a standard which describes how ordered lists and unordered maps, strings booleans and numbers can be represented in a string.(它是一个标准,它描述了有序列表和无序映射,字符串布尔值和数字如何用字符串表示。)
Just like XML and YAML is a way to pass structured information between languages, JSON is the same.(就像XML和YAML是一种在语言之间传递结构化信息的方式一样,JSON是相同的。)
A JavaScript object on the other hand is a physical type.(另一方面,JavaScript对象是物理类型。)
Just like a PHP array, a C++ class/ struct, a JavaScript object is an type internal to JavaScript.(就像PHP数组,C ++类/结构一样,JavaScript对象是JavaScript内部的类型。)
Here's a story.
(这是一个故事。)
Let's imagine you've purchased some furniture from a store, and you want it delivered.(让我们想象一下,你已经从商店购买了一些家具,并且希望它能够送到。)
However the only one left in stock is the display model, but you agree to buy it.(然而,库存中唯一剩下的是显示器型号,但您同意购买它。)
In the shop, the chest-of-drawers you've purchased is a living object:
(在商店里,你购买的抽屉柜是一个生物:)
var chestOfDrawers = { color: "red", numberOfDrawers: 4 }
However, you can't send a chest-of-drawers in the post, so you dismantle it (read, stringify it).
(但是,你不能在帖子中发送抽屉柜,所以你要拆除它(阅读,字符串化)。)
It's now useless in terms of furniture.(现在它在家具方面毫无用处。)
It is now JSON.(它现在是JSON。)
Its in flat pack form.(它采用扁平包装形式。)
{"color":"red","numberOfDrawers":4}
When you receive it, you then rebuild the chest-of-drawers (read, parse it).
(当你收到它,然后你重建抽屉柜(阅读,解析它)。)
Its now back in an object form.(它现在回到了一个对象形式。)
The reason behind JSON/ XML and YAML is to enable data to be transferred between programming languages in a format both participating languages can understand;
(JSON / XML和YAML背后的原因是使数据能够以参与语言可以理解的格式在编程语言之间传输;)
you can't give PHP or C++ your JavaScript object directly;(你不能直接给PHP或C ++你的JavaScript对象;)
because each language represents an object differently under-the-hood.(因为每种语言都表示不同的对象。)
However, because we've stringified the object into JSON notation;(但是,因为我们已经将对象字符串化为JSON表示法;)
ie a standardised way to represent data, we can transmit the JSON representation of the object to another langauge (C++, PHP), they can recreate the JavaScript object we had into their own object based on the JSON representation of the object.(即,一种表示数据的标准化方法,我们可以将对象的JSON 表示传递给另一个语言(C ++,PHP),它们可以根据对象的JSON表示重新创建我们拥有的JavaScript对象。)
It is important to note that JSON cannot represent functions or dates.
(请务必注意,JSON不能表示函数或日期。)
If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation.(如果尝试使用函数成员对对象进行字符串化,则将从JSON表示中省略该函数。)
A date will be converted to a string;(日期将转换为字符串;)
JSON.stringify({ foo: new Date(), blah: function () { alert('hello'); } }); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"