Javascript 对象与 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8294088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:27:26  来源:igfitidea点击:

Javascript object Vs JSON

javascriptjson

提问by testndtv

I want to understand the basic differences clearly between Javascript object and JSON string.

我想清楚地了解 Javascript 对象和 JSON 字符串之间的基本区别。

Let's say I create the following JS variable:

假设我创建了以下 JS 变量:

var testObject = {one: 1,"two":2,"three":3};

Q1. Is the key/property name valid both with/without quotes?(e.g. "one" : 1)

一季度。带/不带引号的键/属性名称是否有效?(例如"one" : 1

If yes, what is the difference?

如果是,有什么区别?

Q2: If I convert the above object using JSON.stringify(testObject), what's the difference between the original JS object and the JSON?

Q2:如果我使用 转换上述对象JSON.stringify(testObject),那么原始 JS 对象和 JSON 之间有什么区别?

I feel they are almost the same. Please elaborate on this.

我觉得他们几乎一样。请详细说明这一点。

Q3: For parsing a JSON string, is the method below recommended?

Q3:解析 JSON 字符串,是否推荐使用以下方法?

var javascriptObj = JSON.parse(jSonString);

回答by Matt

  1. Is the key/property name valid both with/without quotes ?

    The only time you need to enclose a key in quotes when using Object Literal notation is where the key contains a special character (if, :, -etc). It is worth noting that a key in JSON mustbe enclosed in doublequotes.

  2. If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);, what is the difference between the 2 (JS obj and JSON)?

    JSONis a data interchange format. 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. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is an type internal to 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. 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; you can't give PHP or C++ your JavaScript object directly; because each language represents an object differently under-the-hood. However, because we've stringified the object into JSON notation; i.e. a standardised way to represent data, we can transmit the JSON representationof the object to another langauge (C++, PHP), they can recreatethe JavaScript object we had into their own object basedon the JSON representation of the object.

    It is important to note that JSON cannot represent functions or dates. If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation. 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"}"
    
  3. For parsing a JSON string, is the method below recommended? var javascriptObj = JSON.parse(jSonString);

    Yes, but older browsers don't support JSON natively (IE <8). To support these, you should include json2.js.

    If you're using jQuery, you can call jQuery.parseJSON(), which will use JSON.parse()under the hood if it's supported and will otherwise fallback to a custom implementation to parse the input.

  1. 带/不带引号的键/属性名称是否有效?

    你需要使用对象的文字符号时放在引号的关键唯一的一次,其中关键包含特殊字符(if:-等)。值得注意的是,JSON 中的键必须引号括起来。

  2. 如果我使用 将上述对象转换为 JSON var jSonString = JSON.stringify(testObject);,那么 2(JS obj 和 JSON)之间有什么区别?

    JSON是一种数据交换格式。这是一个标准,描述了如何在字符串中表示有序列表和无序映射、字符串布尔值和数字。就像 XML 和 YAML 是一种在语言之间传递结构化信息的方式一样,JSON 也是如此。另一方面,JavaScript 对象是一种物理类型。就像 PHP 数组、C++ 类/结构一样,JavaScript 对象是 JavaScript 内部的类型。

    这是一个故事。假设您从商店购买了一些家具,并希望将其交付。然而,库存中只剩下展示模型,但您同意购买。

    在商店里,你购买的抽屉柜是一个活物:

    var chestOfDrawers = {
        color: "red",
        numberOfDrawers: 4
    }
    

    但是,您不能在邮政中发送抽屉,因此您将其拆除(阅读,将其串起来)。它现在在家具方面毫无用处。现在是 JSON。它是扁平包装形式。

    {"color":"red","numberOfDrawers":4}
    

    当您收到它时,您就可以重建抽屉柜(阅读、解析它)。它现在以对象形式返回。

    JSON/XML 和 YAML 背后的原因是使数据能够以两种参与语言都能理解的格式在编程语言之间传输;你不能直接给 PHP 或 C++ 你的 JavaScript 对象;因为每种语言在幕后都以不同的方式表示一个对象。但是,因为我们已将对象字符串化为 JSON 表示法;即一种标准化的数据表示方式,我们可以将对象的 JSON表示传输到另一种语言(C++、PHP),他们可以根据对象的 JSON 表示将我们拥有的 JavaScript 对象重新创建到他们自己的对象中。

    需要注意的是,JSON 不能表示函数或日期。如果您尝试使用函数成员对对象进行字符串化,则该函数将从 JSON 表示中省略。日期将被转换为字符串;

    JSON.stringify({
        foo: new Date(),
        blah: function () { 
            alert('hello');
        }
    }); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"
    
  3. 对于解析 JSON 字符串,是否推荐使用以下方法? var javascriptObj = JSON.parse(jSonString);

    是的,但较旧的浏览器本身不支持 JSON (IE <8)。为了支持这些,你应该包括json2.js.

    如果您使用 jQuery,则可以调用jQuery.parseJSON()JSON.parse()如果支持,它将在后台使用,否则将回退到自定义实现来解析输入。

回答by Ben Lee

Q1: When defining object literals in javascript, the keys may include quotes or not. There is no difference except that quotes allow you to specify certain keys that would cause the interpreter to fail to parse if you tried them bare. For example, if you wanted a key that was just an exclamation point, you would need quotes:

Q1:在 javascript 中定义对象字面量时,键可能包含或不包含引号。没有什么区别,除了引号允许您指定某些键,如果您尝试使用它们会导致解释器无法解析。例如,如果您想要一个只是感叹号的键,则需要引号:

a = { "!": 1234 } // Valid
a = { !: 1234 } //  Syntax error

In most cases though, you can omit the quotes around keys on object literals.

但在大多数情况下,您可以省略对象文字上的键周围的引号。

Q2: JSON is literally a string representation. It is just a string. So, consider this:

Q2:JSON 实际上是一种字符串表示。它只是一个字符串。所以,考虑一下:

var testObject = { hello: "world" }
var jSonString = JSON.stringify(testObject);

Since testObjectis a real object, you can call properties on it and do anything else you can do with objects:

因为它testObject是一个真实的对象,你可以调用它的属性并做任何你可以对对象做的事情:

testObject.hello => "world"

On the other hand, jsonStringis just a string:

另一方面,jsonString只是一个字符串:

jsonString.hello => undefined

Note one other difference: In JSON, all keys must be quoted. That contrasts with object literals, where the quotes can usually be omitted as per my explanation in Q1.

注意另一个区别:在 JSON 中,所有键都必须被引用。这与对象字面量形成对比,根据我在 Q1 中的解释,通常可以省略引号。

Q3. You can parse a JSON string by using JSON.parse, and this is generally the best way to do it (if the browser or a framework provides it). You can also just use evalsince JSON is valid javascript code, but the former method is recommended for a number of reasons (eval has a lot of nasty problems associated with it).

Q3。您可以使用 解析 JSON 字符串JSON.parse,这通常是最好的方法(如果浏览器或框架提供)。您也可以直接使用,eval因为 JSON 是有效的 javascript 代码,但出于多种原因推荐使用前一种方法(eval 有很多与之相关的令人讨厌的问题)。

回答by mins

Problems solved by JSON

JSON 解决的问题

Let's say you want to exchange regular JavaScript objects between two computers, and you set two rules:

假设您想在两台计算机之间交换常规 JavaScript 对象,并且您设置了两个规则:

  • The transmitted data must be a regular string.
  • Only attributes can be exchanged, methods are not transmitted.
  • 传输的数据必须是常规字符串。
  • 只能交换属性,不传输方法。

Now you create two objects on the first host:

现在您在第一个主机上创建两个对象:

var obj1 = { one: 1,"two":2,"three":3 }; // your example
var obj2 = { one: obj1.one, two: 2, three: obj1.one + obj1.two };

How can you convert those objects into strings for transmission to the second host?

如何将这些对象转换为字符串以传输到第二台主机?

  • For the first object, you could send this string obtained form the literal definition '{ one: 1,"two":2,"three":3 }', but actually you can't read the literal in the script portion of the document (at least not easily). So obj1and obj2must actually be processed the same way.
  • You need to enumerate all attributes and their value, and build a string similar to the object literal.
  • 对于第一个对象,您可以发送从文字定义中获得的字符串'{ one: 1,"two":2,"three":3 }',但实际上您无法读取文档脚本部分中的文字(至少不容易)。因此obj1obj2实际上必须以相同的方式处理。
  • 您需要枚举所有属性及其值,并构建一个类似于对象字面量的字符串。

JSON has been created as a solution to the needs just discussed: It is a set of rules to create a string equivalent to an object by listing all attributes and values (methods are ignored).

创建 JSON 是为了解决刚刚讨论的需求:它是一组规则,通过列出所有属性和值(忽略方法)来创建与对象等效的字符串。

JSON normalizes the use of double-quotes for attribute names and values.

JSON 规范了属性名称和值的双引号使用。

Remember that JSON is a set of rules only (a standard).

请记住,JSON 只是一组规则(标准)。

How many JSON objects are created?

创建了多少 JSON 对象?

Only one, it is automatically created by the JS engine.

只有一个,它是由 JS 引擎自动创建的。

Modern JavaScript engines found in browsers have a native object, also named JSON. This JSON object is able to:

浏览器中的现代 JavaScript 引擎有一个本地对象,也称为 JSON。这个 JSON 对象能够:

  • Decode a string built using JSON standard, using JSON.parse(string). The result is a regular JS object with attributes and values found in the JSON string.

  • Encode attributes / values of a regular JS object using JSON.stringify(). The result is a string compliant with the JSON set of rules.

  • 使用 JSON.parse(string) 解码使用 JSON 标准构建的字符串。结果是具有在 JSON 字符串中找到的属性和值的常规 JS 对象。

  • 使用 JSON.stringify() 对常规 JS 对象的属性/值进行编码。结果是符合 JSON 规则集的字符串。

The (single) JSON object is similar to a codec, it's function is to encode and decode.

(单个)JSON 对象类似于编解码器,它的功能是编码和解码。

Note that:

注意:

  • JSON.parse() doesn't create a JSON object, it creates a regular JS object, there is no difference between an object created using an object literal and an object created by JSON.parse() from a JSON-compliant string.

  • There is only one JSON object, which is used for all conversions.

  • JSON.parse() 不创建 JSON 对象,它创建一个常规的 JS 对象,使用对象字面量创建的对象和由 JSON.parse() 从符合 JSON 的字符串创建的对象之间没有区别。

  • 只有一个 JSON 对象,用于所有转换。

Going back to the questions:

回到问题

  • Q1: The use of single of double quotes is allowed for object literals. Note that the quotes are used optionally for attributes names, and are mandatory for string values. The object literal itself is not surrounded by quotes.

  • Q2: Objects created from literals and using JSON.parse() are strictly the same. These two objects are equivalent after creation:

    var obj1 = { one: 1, "two": 2, "three": 3 };
    var obj2 = JSON.parse('{ "one": "1", "two": "2", "three": "3" }');

  • Q3: On modern browsers JSON.parse()is used to create a JS object from a JSON-compliant string. (jQuery has also an equivalent method that can be used for all browsers).

  • Q1:对象字面量允许使用单引号或双引号。请注意,引号可选择性地用于属性名称,并且对于字符串值是必需的。对象文字本身没有被引号包围。

  • Q2:从文字创建的对象和使用 JSON.parse() 的对象完全相同。这两个对象在创建后是等价的:

    var obj1 = { one: 1, "two": 2, "three": 3 };
    var obj2 = JSON.parse('{ "one": "1", "two": "2", "three": "3" }');

  • Q3:在现代浏览器JSON.parse()上用于从符合 JSON 的字符串创建 JS 对象。(jQuery 也有一个等效的方法,可用于所有浏览器)。

回答by Alnitak

Q1 - in JS you only need to use quotes if the key is a reserved word or if it would otherwise be an illegal token. In JSON you MUST always use double quotes on key names.

Q1 - 在 JS 中,如果键是保留字或者它是非法标记,则只需要使用引号。在 JSON 中,您必须始终在键名上使用双引号。

Q2 - the jsonStringis a serialisedversion of the input object ...

Q2 - 这jsonString是输入对象的序列化版本......

Q3 - which may be deserialisedto an identical looking object using JSON.parse()

Q3 - 可以使用反序列化为相同外观的对象JSON.parse()

回答by Shiva

Question already has good answers posted, I am adding a small example below, which will make it more easy to understand the explanations given in previous answers. Copy paste below snippet to your IDE for better understanding and comment the line containing invalid_javascript_object_no_quotesobject declaration to avoid compile time error.

问题已经发布了很好的答案,我在下面添加了一个小示例,这样可以更容易地理解之前答案中给出的解释。将下面的代码片段复制粘贴到您的 IDE,以便更好地理解并注释包含invalid_javascript_object_no_quotes对象声明的行以避免编译时错误。

// Valid JSON strings(Observe quotes)
valid_json = '{"key":"value"}'
valid_json_2 = '{"key 1":"value 1"}' // Observe the space(special character) in key - still valid


//Valid Javascript object
valid_javascript_object_no_quotes = {
    key: "value"  //No special character in key, hence it is valid without quotes for key
}


//Valid Javascript object
valid_javascript_object_quotes = {
    key:"value",  //No special character in key, hence it is valid without quotes for key
    "key 1": "value 1" // Space (special character) present in key, therefore key must be contained in double quotes  - Valid
}



console.log(typeof valid_json) // string
console.log(typeof valid_javascript_object_no_quotes) // object
console.log(typeof valid_javascript_object_quotes) // object

//Invalid Javascript object 
invalid_javascript_object_no_quotes = {
   key 1: "value"//Space (special character) present in key, since key is not enclosed with double quotes "Invalid Javascript Object"
}