Javascript JSON 和 Object Literal Notation 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2904131/
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-23 02:25:48  来源:igfitidea点击:

What is the difference between JSON and Object Literal Notation?

javascriptjsonobject-notation

提问by pencilCake

Can someone tell me what is the main difference between a JavaScript object defined by using Object Literal Notationand JSON object?

有人能告诉我使用Object Literal NotationJSON object定义的 JavaScript 对象之间的主要区别是什么吗?

According to a JavaScript book it says this is an object defined by using Object Notation:

根据一本 JavaScript 书,它说这是一个使用Object Notation定义的对象

var anObject = {
    property1 : true,
    showMessage : function (msg) { alert(msg) }
};

Why isn't it a JSON object in this case? Just because it is not defined by using quotation marks?

为什么在这种情况下它不是 JSON 对象?仅仅因为它不是用引号定义的吗?

回答by Felix Kling

Lets clarify first what JSONactually is. JSON is a textual, language-independent data-exchange format, much like XML, CSV or YAML.

让我们先澄清一下JSON到底是什么。JSON 是一种文本的、独立于语言的数据交换格式,很像 XML、CSV 或 YAML。

Data can be stored in many ways, but if it should be stored in a text file and be readable by a computer, it needs to follow some structure. JSON is one of the many formats that define such a structure.

数据可以通过多种方式存储,但是如果要将其存储在文本文件中并且可以被计算机读取,则需要遵循某种结构。JSON 是定义这种结构的众多格式之一。

Such formats are typically language-independent, meaning they can be processed by Java, Python, JavaScript, PHP, you name it.

此类格式通常与语言无关,这意味着它们可以由 Java、Python、JavaScript、PHP 处理,您可以随意命名。

In contrast, JavaScriptis a programming language. Of course JavaScript also provides a way to define/describe data, but the syntax is very specific to JavaScript.

相比之下,JavaScript是一种编程语言。当然,JavaScript 也提供了一种定义/描述数据的方法,但语法是非常特定于 JavaScript 的。

As a counter example, Python has the concept of tuples, their syntax is (x, y). JavaScript doesn't have something like this.

作为一个反例,Python 有tuples的概念,它们的语法是(x, y). JavaScript 没有这样的东西。



Lets look at the syntactical differences between JSON and JavaScript object literals.

让我们看看 JSON 和 JavaScript 对象字面量之间的语法差异。

JSON has the following syntactical constraints:

JSON 具有以下语法约束:

  • Object keysmust be strings(i.e. a character sequence enclosed in double quotes ").
  • The values can be either:
    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null
  • Duplicate keys ({"foo":"bar","foo":"baz"}) produce undefined, implementation-specific results; the JSON specification specifically does not define their semantics
  • 对象必须是字符串(即用双引号括起来的字符序列")。
  • 这些值可以是:
    • 一个字符串
    • 一个号码
    • 一个(JSON)对象
    • 数组
    • true
    • false
    • null
  • 重复键 ( {"foo":"bar","foo":"baz"}) 产生未定义的、特定于实现的结果;JSON 规范没有明确定义它们的语义

In JavaScript, object literals can have

在 JavaScript 中,对象字面量可以有

  • String literals, number literals or identifier names as keys (since ES6, keys can now also be computed, which introduces yet another syntax).
  • The values can be any valid JavaScript expression, including function definitions and undefined.
  • Duplicate keys produce defined, specified results (in loose mode, the latter definition replaces the former; in strict mode, it's an error).
  • 字符串字面量、数字字面量或标识符名称作为键(从 ES6 开始,现在也可以计算键,这引入了另一种语法)。
  • 这些值可以是任何有效的 JavaScript 表达式,包括函数定义和undefined.
  • 重复的键产生定义的、指定的结果(在松散模式下,后一个定义取代了前一个;在严格模式下,这是一个错误)。


Knowing that, just by looking at the syntax, your example is not JSON because of two reasons:

知道,仅通过查看语法,您的示例不是 JSON,原因有两个:

  1. Your keys are not strings (literals). They are identifier names.
  2. You cannot assign a function as a value to a "JSON object" (because JSON doesn't define any syntax for functions).
  1. 您的键不是字符串(文字)。它们是标识符名称
  2. 您不能将函数作为值分配给“JSON 对象”(因为 JSON 没有为函数定义任何语法)。

But most importantly, to repeat my explanation from the beginning: You are in a JavaScript context. You define a JavaScript object. If any, a "JSON object" can only be contained in a string:

但最重要的是,从头开始重复我的解释:您处于 JavaScript 上下文中。您定义一个 JavaScript 对象。如果有,“JSON 对象”只能包含在字符串中:

 var obj = {foo: 42}; // creates a JavaScript object (this is *not* JSON)
 var json = '{"foo": 452}'; // creates a string containing JSON

That is, if you're writing JavaScript source code, and not dealing with a string, you're not dealing with JSON. Maybe you received the data as JSON (e.g., via ajax or reading from a file), but once you or a library you're using has parsed it, it's not JSON anymore.

也就是说,如果您正在编写 JavaScript 源代码,而不是处理string,那么您就不是在处理 JSON。也许您收到的数据是 JSON(例如,通过 ajax 或从文件中读取),但是一旦您或您正在使用的库解析了它,它就不再是 JSON。



Only because object literals and JSON look similar, it does not mean that you can name them interchangeably.See also There's no such thing as a "JSON Object".

仅仅因为对象字面量和 JSON 看起来相似,并不意味着您可以互换命名它们。另请参阅没有“JSON 对象”这样的东西

回答by Quentin

JSONhas a much more limited syntax including:

JSON 的语法更为有限,包括:

  • Key values must be quoted
  • Strings must be quoted with "and not '
  • You have a more limited range of values (e.g. no functions allowed)
  • 必须引用键值
  • 字符串必须用"和 不'
  • 您的值范围更有限(例如,不允许使用任何函数)

回答by Nick Perkins

There is really no such thing as a "JSON Object".

真的没有“JSON 对象”这样的东西。

The JSON spec is a syntax for encoding data as a string. What people call a "JSON Object" ( in javascript ) is really just an ordinary javascript object that has (probably) been de-serialized from a valid JSON string, and can be easily re-serialized as a valid JSON string. This generally means that it contains only data ( and not functions ). It also means that there are no dates, because JSON does not have a date type ( probably the most painful thing about JSON ;)

JSON 规范是一种将数据编码为字符串的语法。人们所说的“JSON 对象”(在 javascript 中)实际上只是一个普通的 javascript 对象,它(可能)从有效的 JSON 字符串中反序列化,并且可以轻松地重新序列化为有效的 JSON 字符串。这通常意味着它只包含数据(而不是函数)。这也意味着没有日期,因为 JSON 没有日期类型(可能是关于 JSON 最痛苦的事情;)

Furthermore, (side-rant...) when people talk about a "JSON Object", they almost always mean data that has the "curly-braces" at the top-level. This corresponds nicely to a javascript object. However, the JSON spec does not require that there be a single "curly-braces" object at the top-level of a JSON string. It is perfectly valid JSON to have a list at the top-level, or even to have just a single value. So, while every "JSON Object" corresponds to valid JSON, not all valid JSON strings correspond to what we would call a "JSON Object"! ( because the string could represent a list or an atomic value )

此外,(旁白...)当人们谈论“JSON 对象”时,他们几乎总是指在顶层具有“花括号”的数据。这很好地对应于一个 javascript 对象。但是,JSON 规范不要求在 JSON 字符串的顶层有一个“花括号”对象。在顶级有一个列表,甚至只有一个值,这是完全有效的 JSON。因此,虽然每个“JSON 对象”都对应于有效的 JSON,但并非所有有效的 JSON 字符串都对应于我们所说的“JSON 对象”!(因为字符串可以代表一个列表或一个原子值)

回答by ma11hew28

According to JSON in JavaScript,

根据JavaScript 中的 JSON

JSON is a subsetof the object literal notation of JavaScript.

JSON 是JavaScript 的对象字面量表示法的一个子集

In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around.

换句话说,有效的 JSON 也是有效的 JavaScript 对象文字表示法,但不一定相反。

In addition to reading the documentation, as @Filix King suggested, I also suggest playing around with the JSONLint online JSON validator. That's how I learned that the keys of JSON objects must be strings.

除了阅读文档,正如@Filix King 建议的那样,我还建议使用JSONLint 在线 JSON 验证器。这就是我如何了解到 JSON 对象的键必须是字符串。

回答by Yash

JSON: The Fat-Free Alternative to XML

JSON:XML 的无脂肪替代品

JSON has been widely adopted by people who found that it made it a lot easier to produce distributed applications and services. The official Internet media type for JSON is application/jsonRFC 4627. JSON filenames use the extension .json.

JSON 已被人们广泛采用,他们发现它使生成分布式应用程序和服务变得更加容易。JSON 的官方 Internet 媒体类型是application/jsonRFC 4627. JSON 文件名使用扩展名.json.



? JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. JSON has been used to exchange data between applications written in any Programming language.

? JavaScript Object Notation ( JSON) 是一种轻量级、基于文本、独立于语言的数据交换格式。JSON 已用于在以任何编程语言编写的应用程序之间交换数据。

The JSON object is a single object that contains two functions, parse and stringify, that are used to parse and construct JSON texts.

  • JSON.stringify produces a String that conforms to the following JSON grammar.
  • JSON.parse accepts a String that conforms to the JSON grammar.

The parseJSON method will be included in the Fourth Edition of ECMAScript. In the meantime, a JavaScript implementation is available at json.org.

JSON 对象是一个单一的对象,它包含两个函数 parse 和 stringify,用于解析和构造 JSON 文本。

  • JSON.stringify 生成符合以下 JSON 语法的字符串。
  • JSON.parse 接受一个符合 JSON 语法的 String。

parseJSON 方法将包含在Fourth Edition of ECMAScript. 同时,在 json.org 上提供了 JavaScript 实现。

var objLiteral = {foo: 42}; // JavaScript Object
console.log('Object Literal : ', objLiteral ); // Object {foo: 42}foo: 42__proto__: Object

// This is a JSON String, like what you'd get back from an AJAX request.
var jsonString = '{"foo": 452}';
console.log('JOSN String : ', jsonString ); // {"foo": 452}

// This is how you deserialize that JSON String into an Object.
var serverResposnceObject = JSON.parse( jsonString );
console.log('Converting Ajax response to JavaScript Object : ', serverResposnceObject); // Object {foo: 42}foo: 42 __proto__: Object

// And this is how you serialize an Object into a JSON String.
var serverRequestJSON = JSON.stringify( objLiteral );
console.log('Reqesting server with JSON Data : ', serverRequestJSON); // '{"foo": 452}'

JSON is subset of JavaScript. Javascriptwas derived from the ECMAScript Programming Language Standard.

JSON 是 JavaScript 的子集。Javascript源自 ECMAScript 编程语言标准。



? ECMAScript

? ECMAScript

ECMAScript has grown to be one of the world's most widely used general purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications.ECMAScript is based on several originating technologies, the most well-known being JavaScript(Netscape Communications)) and JScript(Microsoft Corporation).). Though before 1994, ECMA was known as "European Computer Manufacturers Association", after 1994, when the organization became global, the "trademark" "Ecma" was kept for historical reasons.

ECMAScript 已经成长为世界上使用最广泛的通用编程语言之一。它以嵌入在 Web 浏览器中的语言而闻名,但也被广泛用于服务器和嵌入式应用程序。ECMAScript 基于几种原始技术,最著名的是JavaScript(Netscape Communications)) 和JScript(Microsoft Corporation).)虽然在 1994 年之前,ECMA 被称为“欧洲计算机制造商协会”,但在 1994 年之后,当该组织走向全球时,由于历史原因,“商标”“Ecma”被保留了下来。

ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript are called "Dialects".

ECMAScript 是一种语言,而 JavaScript、JScript 甚至 ActionScript 被称为"Dialects".

Dialects have been derived from the same language. They are are quite similar to each other as they have been derived from the same language but they have undergone some changes. A dialect is a variation in the language itself. It is derived from a single language.

  • SQL Language - Hibernate MySQL Dialect, Oracle Dialect,.. which have some changes or added functionality.

方言起源于同一种语言。它们彼此非常相似,因为它们源自相同的语言,但它们发生了一些变化。方言是语言本身的变体。它源自单一语言。

  • SQL 语言 - Hibernate MySQL 方言、Oracle 方言等,其中有一些更改或添加了功能。

Information about the browser and computer of your users.

有关您用户的浏览器和计算机的信息。

navigator.appName // "Netscape"

ECMAScript is the scripting language that forms the basis of JavaScript. JavaScriptlanguage resources.

ECMAScript 是构成 JavaScript 基础的脚本语言。.JavaScriptlanguage resources

ECMA-262 Links
Initial Edition, June 1997PDF.
2nd Edition, August 1998PDF.
3rd Edition, December 1999PDF.
5th Edition, December 2009PDF.
5.1 Edition, June 2011HTML.
6th Edition, June 2015HTML.
7?? Edition, June 2016HTML.
8th edition, June 2017HTML.
9th Edition, 2018HTML.

ECMA-262 Links
Initial Edition, June 1997PDF.
2nd Edition, August 1998PDF.
3rd Edition, December 1999PDF.
5th Edition, December 2009PDF.
5.1 Edition, June 2011HTML.
6th Edition, June 2015HTML.
7?? Edition, June 2016HTML.
8th edition, June 2017HTML.
9th Edition, 2018HTML.

NOTE ?4th editionof ECMAScript not published as the work was incomplete.

笔记 ?ECMAScript第 4 版出版,因为工作不完整



JSON defines a small set of formatting rules for the portable representation of structured data.

JSON 为结构化数据的可移植表示定义了一小组格式规则。

  1. ? Key values must be quoted, only Strings are allowed for keys. If you use other than String it will convert to String. But not recommended to use keys other than String's. Check an example like this - { 'key':'val' }over RFC 4627 - jsonformatter

    var storage = {
      0 : null,
      1 : "Hello"
    };
    console.log( storage[1] ); // Hello
    console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
    
    var objLiteral = {'key1':'val1'};
        var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
        var obj = { k: 'v' }, obj2 = { k2: 'v2' };
        var fun = function keyFun() {} ;
    
    objLiteral[ arr ] = 'ArrayVal';     objLiteral[ arr2 ] = 'OverridenArrayVal';
    objLiteral[ obj ] = 'ObjectVal';    objLiteral[ obj2 ] = 'OverridenObjectVal';
    objLiteral[ fun ] = 'FunctionVal';
    
    console.log( objLiteral );
    // Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
    console.log( JSON.stringify( objLiteral ) );
    // {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
    console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
    // Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
    
    console.log('Accessing Array  Val : ', objLiteral[ [10,20] ] );
    console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
    console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
    
  2. ? JSON Strings must be quoted with " and not '. A string is very much like a C or Java string. Strings should be wrapped in double quotes.

    • Literals are fixed values, not variables, that you literally provide in your script.
    • A string is a sequence of zero or more characters wrapped in quotes with backslash escapement, the same notation used in most programming languages.
      • - Special Symbols are allowed in String but not recomended to use.
      • \" - Special characters can be escaped. But not recomended to escape (') Single Quotes. In Strict mode it will throw and Error - SyntaxError: Unexpected token ' in JSON

    Check with this code { "Hai\" \n Team ":5, "Bye \'": 7 }over online JSON Edtions. ModesnotStrict,Strinct.

    var jsonString = "{'foo': 452}"; // {'foo': 452}
    var jsonStr = '{"foo": 452}'; // {"foo": 452}
    
    JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
    JSON.parse( jsonStr ); // Object {foo: 452}
    
    objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
    objLiteral.key2 = 'val';
    
    // objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
    objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key?3": "val"}
    
    JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
    
  1. ? 键值必须用引号引起来,键只允许使用字符串。如果您使用 String 以外的其他内容,它将转换为 String。但不建议使用 String 以外的键。检查这样的例子 -{ 'key':'val' }结束RFC 4627 - jsonformatter

    var storage = {
      0 : null,
      1 : "Hello"
    };
    console.log( storage[1] ); // Hello
    console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
    
    var objLiteral = {'key1':'val1'};
        var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
        var obj = { k: 'v' }, obj2 = { k2: 'v2' };
        var fun = function keyFun() {} ;
    
    objLiteral[ arr ] = 'ArrayVal';     objLiteral[ arr2 ] = 'OverridenArrayVal';
    objLiteral[ obj ] = 'ObjectVal';    objLiteral[ obj2 ] = 'OverridenObjectVal';
    objLiteral[ fun ] = 'FunctionVal';
    
    console.log( objLiteral );
    // Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
    console.log( JSON.stringify( objLiteral ) );
    // {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
    console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
    // Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
    
    console.log('Accessing Array  Val : ', objLiteral[ [10,20] ] );
    console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
    console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
    
  2. ? JSON 字符串必须用 " 而不是 ' 引用。字符串非常类似于 C 或 Java 字符串。字符串应该用双引号括起来。

    • 文字是您在脚本中提供的固定值,而不是变量。
    • 字符串是用反斜杠转义的引号包裹的零个或多个字符的序列,这与大多数编程语言中使用的符号相同。
      • - 字符串中允许使用特殊符号,但不建议使用。
      • \" - 可以转义特殊字符。但不建议转义 (') 单引号。在严格模式下,它会抛出错误 - SyntaxError: Unexpected token ' in JSON

    { "Hai\" \n Team ":5, "Bye \'": 7 }通过在线 JSON 版本检查此代码。ModesnotStrict,Strinct.

    var jsonString = "{'foo': 452}"; // {'foo': 452}
    var jsonStr = '{"foo": 452}'; // {"foo": 452}
    
    JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
    JSON.parse( jsonStr ); // Object {foo: 452}
    
    objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
    objLiteral.key2 = 'val';
    
    // objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
    objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key?3": "val"}
    
    JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
    

Object Property accessorsprovide access to an object's properties by using the dot notation or the bracket notation.

对象属性访问器通过使用点表示法或括号表示法提供对对象属性的访问。

  1. ? You have a more limited range of values (e.g. no functions allowed). A value can be a string in double quotes, number, boolean, null, object, or array. These structures can be nested.

    var objLiteral = {};
    objLiteral.funKey = function sayHello() {
        console.log('Object Key with function as value - Its outcome message.');
    };
    
    objLiteral['Key'] = 'Val';
    
    console.log('Object Literal Fun : ', objLiteral );
    // Object Literal Fun :  Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
    console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
    
  1. ? 您的值范围更有限(例如,不允许使用任何函数)。值可以是双引号中的字符串、数字、布尔值、空值、对象或数组。这些结构可以嵌套。

    var objLiteral = {};
    objLiteral.funKey = function sayHello() {
        console.log('Object Key with function as value - Its outcome message.');
    };
    
    objLiteral['Key'] = 'Val';
    
    console.log('Object Literal Fun : ', objLiteral );
    // Object Literal Fun :  Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
    console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
    

enter image description here

在此处输入图片说明



? JavaScriptis the most popular implementation of the ECMAScript Standard. The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.

? JavaScript是 ECMAScript 标准最流行的实现。Javascript 的核心功能基于 ECMAScript 标准,但 Javascript 还具有 ECMA 规范/标准中没有的其他附加功能。每个浏览器都有一个 JavaScript 解释器。

JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.

JavaScript 是一种动态类型语言。这意味着您不必在声明变量时指定它的数据类型,并且在脚本执行期间会根据需要自动转换数据类型。

Literals:

Literals

'37' - 7    // 30
'37' + 7    // "377"
+'37' + 7   // 44
+'37'       // 37
'37'        // "37"

parseInt('37');     // 37
parseInt('3.7');    // 3

parseFloat(3.7);    // 3.7

// An alternative method of retrieving a number from a string is with the + (unary plus) operator:
+'3.7'              // 3.7

Object literalsRFC 7159

Object literalsRFC 7159

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

对象结构表示为一对大括号,围绕零个或多个名称/值对(或成员)。名称是一个字符串。每个名称后面都有一个冒号,将名称与值分开。单个逗号将值与以下名称分开。对象内的名称应该是唯一的。

ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object's prototype) associated with its constructor. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.

ECMAScript 支持基于原型的继承。每个构造函数都有一个关联的原型,并且由该构造函数创建的每个对象都有一个对其构造函数关联的原型(称为对象的原型)的隐式引用。此外,原型可能具有对其原型的非空隐式引用,依此类推;这称为原型链。

In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.

在基于类的面向对象语言中,一般情况下,状态由实例承载,方法由类承载,继承只是结构和行为。在 ECMAScript 中,状态和方法由对象承载,结构、行为和状态都是继承的。

A prototype is an object used to implement structure, state, and behavior inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor's associated prototype for the purpose of resolving property references. The constructor's associated prototype can be referenced by the program expression constructor.prototype, and properties added to an object's prototype are shared, through inheritance, by all objects sharing the prototype.

原型是用于在 ECMAScript 中实现结构、状态和行为继承的对象。当构造函数创建对象时,该对象隐式引用构造函数的关联原型以解析属性引用。构造函数的关联原型可以被程序表达式constructor.prototype 引用,并且添加到对象原型的属性通过继承被共享原型的所有对象共享。

回答by Daniele D.

For the ones who still think that RFC are more important than blogs and opinion based misconceptions, let's try to answer clarifying some points. I'm not going to repeat all the correct differences already mentioned in previous answers, here I'm just trying adding value summarizing some crucial part rfc7159

对于那些仍然认为 RFC 比博客和基于意见的误解更重要的人,让我们尝试回答澄清一些问题。我不会重复之前答案中已经提到的所有正确差异,在这里我只是尝试添加值总结一些关键部分 rfc7159

Extracts from https://tools.ietf.org/html/rfc7159

摘自https://tools.ietf.org/html/rfc7159

  1. JavaScript ObjectNotation (JSON) is a text format for the serialization of structured data. It is derived from the objectliterals of JavaScript, as defined in the ECMAScript Programming Language Standard, Third Edition [ECMA-262].
  2. JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objectsand arrays).
  3. An objectis an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
  4. begin-object= ws %x7B ws ; { left curly bracket
  5. end-object= ws %x7D ws ; } right curly bracket
  6. A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true
  7. An objectstructure is represented as a pair of curly brackets
  8. The names within an objectSHOULD be unique. object= begin-object[ member *( value-separator member ) ] end-object
  9. An objectwhose names are all unique is interoperable in the sense that all software implementations receiving that objectwill agree on the name-value mappings. When the names within an objectare not unique, the behavior of software that receives such an objectis unpredictable.
  10. Examples (from page 12 of RFC)

    This is a JSON object:

          {
            "Image": {
                "Width":  800,
                "Height": 600,
                "Title":  "View from 15th Floor",
                "Thumbnail": {
                    "Url":    "http://www.example.com/image/481989943",
                    "Height": 125,
                    "Width":  100
                },
                "Animated" : false,
                "IDs": [116, 943, 234, 38793]
              }
          }
    

    Its Image member is an objectwhose Thumbnail member is an objectand whose IDs member is an array of numbers.

  1. JavaScript ObjectNotation (JSON) 是一种用于结构化数据序列化的文本格式。它源自 JavaScript的对象字面量,如 ECMAScript 编程语言标准第三版 [ECMA-262] 中所定义。
  2. JSON 可以表示四种基本类型(字符串、数字、布尔值和 null)和两种结构化类型(对象和数组)。
  3. 一个对象是零个或多个名称/值对,其中一个名称是字符串的无序集合和一个值是一个字符串,数字,布尔值,null,对象,或阵列。
  4. 开始对象= ws %x7B ws ; { 左大括号
  5. 最终对象= ws %x7D ws ; } 右大括号
  6. JSON 值必须是对象、数组、数字或字符串,或以下三个字面名称之一: false null tr​​ue
  7. 一个对象的结构被表示为一对大括号
  8. 对象内的名称应该是唯一的。 object= begin-object[ member *( value-separator member ) ] end-object
  9. 名称都是唯一的对象是可互操作的,因为接收该对象的所有软件实现都将同意名称-值映射。当对象内的名称不唯一时,接收此类对象的软件的行为是不可预测的。
  10. 示例(来自 RFC 的第 12 页)

    这是一个 JSON 对象:

          {
            "Image": {
                "Width":  800,
                "Height": 600,
                "Title":  "View from 15th Floor",
                "Thumbnail": {
                    "Url":    "http://www.example.com/image/481989943",
                    "Height": 125,
                    "Width":  100
                },
                "Animated" : false,
                "IDs": [116, 943, 234, 38793]
              }
          }
    

    它的 Image 成员是一个对象,其 Thumbnail 成员是一个对象,其 IDs 成员是一个数字数组。

There is really no such thing as a "JSON Object".

真的没有“JSON 对象”这样的东西。

Really?

真的吗?

回答by pencilCake

As far as I understand the main difference is the flexibility.

据我了解,主要区别在于灵活性

JSON is a kind of wrapper on "JavaScript Object Notation" which forces users to obey more strict rules for defining the objects. And it does this by limiting the possible object declaration ways provided by JavaScript Object Notation feature.

JSON 是一种“JavaScript Object Notation”的包装器,它强制用户遵守更严格的定义对象的规则。它通过限制 JavaScript Object Notation 特性提供的可能的对象声明方式来做到这一点。

As a result we have a simpler and more standardized objects which suits better on data-exchange between platforms.

因此,我们有一个更简单、更标准化的对象,它更适合平台之间的数据交换。

So basically, the newObject in my example above is an object defined by using JavaScript Objeect Notation; but it is not a 'valid' JSON object because it does not follow the rules that JSON standards require.

所以基本上,我上面例子中的 newObject 是一个使用 JavaScript 对象表示法定义的对象;但它不是“有效”的 JSON 对象,因为它不遵循 JSON 标准要求的规则。

This link is also quite helpful: http://msdn.microsoft.com/en-us/library/bb299886.aspx

这个链接也很有帮助:http: //msdn.microsoft.com/en-us/library/bb299886.aspx

回答by Razi Syed 'Abdi'

First you should know what JSON is:

首先你应该知道什么是 JSON:

It is language agnostic data-interchange format. The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

它是与语言无关的数据交换格式。JSON 的语法受到 JavaScript Object Literal 表示法的启发,但它们之间存在差异。

For example, in JSON all keys must be quoted, while in object literals this is not necessary:

例如,在 JSON 中,所有键都必须被引用,而在对象文字中,这不是必需的:

// JSON: { "foo": "bar" }

// JSON: { "foo": "bar" }

// Object literal: var o = { foo: "bar" }; The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:

// 对象字面量:var o = { foo: "bar" }; JSON 上的引号是强制性的,因为在 JavaScript(更确切地说是在 ECMAScript 3rd. Edition 中)中,不允许使用保留字作为属性名称,例如:

var o = { if: "foo" }; // SyntaxError in ES3 While, using a string literal as a property name (quoting the property name) gives no problems:

var o = { if: "foo" }; // ES3 中的 SyntaxError While,使用字符串字面量作为属性名(引用属性名)没有问题:

var o = { "if": "foo" }; So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.

var o = { "if": "foo" }; 因此,对于“兼容性”(可能是简单的评估?),引号是强制性的。

The data types in JSON are also restricted to the following values:

JSON 中的数据类型也仅限于以下值:

string number object array A literal as: true false null The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.

string number object array 一个字面量:true false null Strings 的语法发生了变化。它们必须用双引号分隔,而在 JavaScript 中,您可以交替使用单引号或双引号。

// Invalid JSON: { "foo": 'bar' } The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.

// Invalid JSON: { "foo": 'bar' } Numbers 接受的 JSON 语法也发生了变化,在 JavaScript 中你可以使用十六进制文字,例如 0xFF,或(臭名昭著的)八进制文字,例如 010。在 JSON 中你可以使用只有十进制文字。

// Invalid JSON: { "foo": 0xFF }

// 无效的 JSON: { "foo": 0xFF }

回答by Willem van der Veen

Javascript Object Literal vs JSON:

Javascript 对象文字与 JSON:

  • Object literal syntax is a very convenient way to create javascript objects
  • The JSONlanguage, which stands for 'Javascript object notation', has its syntax derived from javascript object literal syntax. It is used as a programming language independent textual data transfer format.
  • 对象字面量语法是一种非常方便的创建 javascript 对象的方式
  • JSON语言代表“Javascript 对象符号”,其语法源自 javascript 对象文字语法。它用作独立于编程语言的文本数据传输格式。

Example:

例子:

JS object notation, used in JS to create objects in the code conveniently:

JS 对象表示法,在 JS 中用来方便地在代码中创建对象:

const JS_Object = {
  1: 2,  // the key here is the number 1, the value is the number 2
  a: 'b', // the key is the string a, the value is the string b
  func: function () { console.log('hi') }
  // the key is func, the value is the function
}


Example of JSON:

JSON 示例:

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}

Main differences:

主要区别:

  • All object keys in JSON must be strings. In Javascript object keys can be strings or numbers

  • All strings in JSON must be quoted in "double quotes". Whereas in Javascript both single quotes and double quotes are allowed. Even with no quotes in the Javascript object notation the object keys are implicitly casted to strings.

  • In JSON a function cannot be defined as a value of an object (since this is Javascript specific). In Javascript this is completely legal.

  • JSON 中的所有对象键都必须是字符串。在 Javascript 对象键可以是字符串或数字

  • JSON 中的所有字符串都必须用“双引号”括起来。而在 Javascript 中,单引号和双引号都是允许的。即使在 Javascript 对象符号中没有引号,对象键也会隐式转换为字符串。

  • 在 JSON 中,函数不能定义为对象的值(因为这是特定于 Javascript 的)。在 Javascript 中,这是完全合法的。

Javascript build in JSONobject:

Javascript 内置JSON对象:

JSONobjects can be easily converted to Javascript and vice versa using the built in JSONobject which Javascript offers in its runtime. For example:

JSON使用JSONJavascript 在其运行时提供的内置对象,可以轻松地将对象转换为 Javascript,反之亦然。例如:

const Object = {
  property1: true,
  property2: false,
}; // creating object with JS object literal syntax

const JSON_object = JSON.stringify(Object);  // stringify JS object to a JSON string

console.log(JSON_object); // note that the (string) keys are in double quotes

const JS_object = JSON.parse(JSON_object);  // parse JSON string to JS object

console.log(JS_object.property1, JS_object.property2); 
// accessing keys of the newly created object

回答by Kamil Kie?czewski

Here is one surprising difference: you can not use undefinedin json and all object fields with undefined values will disappear after JSON.stringify

这是一个令人惊讶的区别:您不能undefined在 json 中使用,并且所有具有未定义值的对象字段将在JSON.stringify

let object =  { "a": undefined } ;

let badJSON= '{ "a": undefined }';


console.log('valid JS object :', object );
console.log('JSON from object:', JSON.stringify(object) );
console.log('invalid json    :', JSON.parse(badJSON) );