本文介绍了JSON 和 JavaScript 对象有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JSON 和 JavaScript 对象的新手.

I am new to JSON and JavaScript objects.

  • 谁能解释一下 JSON 和 JavaScript 对象之间的区别?
  • 它们有什么用途?
  • 一种比另一种更好吗?还是视情况而定?
  • 什么时候用,什么情况下?
  • 最初为什么要创建 JSON?它的主要目的是什么?
  • 谁能举例说明何时应该使用 JSON 而不是 JavaScript 对象,反之亦然?

推荐答案

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

First you should know what JSON is:

  • 它是语言不可知数据交换格式.
  • It is language agnostic data-interchange format.

JSON 的语法受到 JavaScript Object Literal 表示法的启发,但它们之间存在差异.

The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

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

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

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

// Object literal:
var o = { foo: "bar" };

引号在 JSON 上是强制性的,因为在 JavaScript(更确切地说是在 ECMAScript 3rd. 版中)中,不允许使用保留字作为属性名称,例如:

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 = { 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" };

所以对于兼容性"(也许是简单的评估?)引号是强制性的.

So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.

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

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

  • string
  • 编号
  • 对象
  • 数组
  • 文字如下:
    • true
    • null

    Strings 的语法发生了变化.它们必须双引号分隔,而在 JavaScript 中,您可以交替使用单引号或双引号.

    The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.

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

    Numbers 接受的 JSON 语法也发生了变化,在 JavaScript 中您可以使用十六进制文字,例如 0xFF,或(臭名昭著的)八进制文字,例如.在 JSON 中,您只能使用十进制文字.

    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": 0xFF }
    

    这篇关于JSON 和 JavaScript 对象有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:27