什么是 JSON,我为什么要使用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/383692/
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
What is JSON and why would I use it?
提问by Ben
I've looked on wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it.
我查看了维基百科并在谷歌上搜索并阅读了官方文档,但我仍然没有真正理解什么是 JSON,以及我为什么要使用它。
I have been building applications using PHP, MySQL and Javascript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?
我已经使用 PHP、MySQL 和 Javascript/HTML 构建应用程序有一段时间了,如果 JSON 可以做一些事情来让我的生活更轻松、我的代码更好或我的用户界面更好,那么我想了解它。有人能给我一个简洁的解释吗?
回答by Andreas Grech
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
JSON(JavaScript Object Notation)是一种用于数据交换的轻量级格式。它基于 JavaScript 语言的一个子集(对象在 JavaScript 中构建的方式)。正如MDN 中所述,有些 JavaScript 不是 JSON,有些 JSON 不是 JavaScript。
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627by Douglas Crockford), it has been the preferred format because it is much more lightweight
使用它的一个示例是 Web 服务响应。在“旧”时代,Web 服务使用 XML 作为传输回数据的主要数据格式,但自从 JSON 出现(JSON 格式由 Douglas Crockford在RFC 4627 中指定),它一直是首选格式,因为它包含更多轻的
You can find a lot more info on the official JSON web site.
您可以在官方JSON 网站上找到更多信息。
JSON is built on two structures:
JSON 建立在两种结构上:
- A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
- 名称/值对的集合。在各种语言中,这被实现为对象、记录、结构、字典、哈希表、键控列表或关联数组。
- 值的有序列表。在大多数语言中,这被实现为数组、向量、列表或序列。
JSON Structure
JSON 结构
Here is an example of JSON data:
以下是 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 in JavaScript
JavaScript 中的 JSON
JSON (in Javascript) is a string!
JSON(在 Javascript 中)是一个字符串!
People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.
人们通常假设所有 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"}'. xis an object of type stringnot 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"}');, xis now an object but this is not JSON anymore.
在 Javascriptvar x = {x:y}中不是 JSON,这是一个Javascript 对象。两者不是一回事。JSON 等价物(以 Javascript 语言表示)将是var x = '{"x":"y"}'. x是一个字符串类型的对象,而不是它自己的对象。要将其转换为完全成熟的 Javascript 对象,您必须首先解析它,var x = JSON.parse('{"x":"y"}');,x现在是一个对象,但这不再是 JSON。
When working with JSON and JavaScript, you may be tempted to use the evalfunction 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).
使用 JSON 和 JavaScript 时,您可能会想使用该eval函数来评估回调中返回的结果,但不建议这样做,因为有两个字符 (U+2028 & U+2029) 在 JSON 中有效但在 JavaScript 中无效(在此处阅读更多内容)。
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 hereand here is a direct linkto the js file. Every major browser nowadays has its own implementationfor this.
因此,必须始终尝试使用 Crockford 的脚本,该脚本在评估之前检查有效的 JSON。脚本解释的链接可以在这里找到,这里是js 文件的直接链接。现在每个主要的浏览器都有自己的实现。
Example on how to use the JSON parser (with the json from the above code snippet):
关于如何使用 JSON 解析器的示例(使用上述代码片段中的 json):
//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:
JSON 解析器还提供了另一种非常有用的方法,stringify. 该方法接受一个 JavaScript 对象作为参数,并返回一个 JSON 格式的字符串。当您想将数据发送回服务器时,这很有用:
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}
The above two methods (parseand stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
上述两个方法(parse和stringify)还带了第二个参数,这个函数会在最终结果的每一层为每个键和值调用,每个值都会被你输入的函数的结果替换。(更多关于这个在这里)
Btw, for all of you out there who think JSON is just for JavaScript, check out this postthat explains and confirms otherwise.
顺便说一句,对于那些认为 JSON 仅适用于 JavaScript 的人,请查看这篇文章,其中解释并确认了其他情况。
References
参考
回答by BKSpurgeon
The Concept Explained - No Code or Technical Jargon
概念解释 - 没有代码或技术术语
What is JSON? – How I explained it to my wifeTM
什么是 JSON?– 我是如何向我妻子TM解释的
Me:“It's basically a way of communicating with someone in writing....but with very specific rules.
我:“这基本上是一种以书面形式与某人交流的方式......但有非常具体的规则。
Wife:yeah....?
老婆:是吗……?
Me:In prosaic English, the rules are pretty loose: just like with cage fighting. Not so with JSON. There are many ways of describing something:
我:在平淡的英语中,规则非常宽松:就像笼子里的格斗一样。JSON 并非如此。描述事物的方式有很多种:
? Example 1: Our family has 4 people: You, me and 2 kids.
? 示例 1:我们家有 4 口人:你、我和 2 个孩子。
? Example 2: Our family: you, me, kid1 and kid2.
? 示例2:我们的家庭:你、我、kid1 和kid2。
? Example 3: Family: [ you, me, kid1, kid2]
? 示例 3:家庭:[你、我、kid1、kid2]
? Example 4: we got 4 people in our family: mum, dad, kid1 and kid2.
? 示例 4:我们家有 4 个人:妈妈、爸爸、孩子 1 和孩子 2。
Wife:Why don't they just use plain English instead?
妻子:他们为什么不使用简单的英语呢?
Me:They would, but remember we're dealing with computers. A computer is stupid and is not going to be able to understand sentences. So we gotta be really specific when computers are involved otherwise they get confused. Furthermore, JSON is a fairly efficient way of communicating, so most of the irrelevant stuff is cut out, which is pretty hand. If you wanted to communicate our family, to a computer, one way you could do so is like this:
我:他们会的,但请记住我们正在处理计算机。计算机是愚蠢的,无法理解句子。因此,当涉及计算机时,我们必须非常具体,否则他们会感到困惑。此外,JSON 是一种相当有效的通信方式,因此大部分不相关的东西都被删掉了,这很实用。如果您想通过计算机与我们的家人沟通,您可以这样做的一种方法是这样的:
{
"Family" : ["Me", "Wife", "Kid1", "Kid2"]
}
……and that is basically JSON. But remember, you MUST obey the JSON grammar rules. If you break those rules, then a computer simply will not understand (i.e. parse) what you are writing.
……这基本上是 JSON。但请记住,您必须遵守 JSON 语法规则。如果您违反这些规则,那么计算机将无法理解(即解析)您正在编写的内容。
Wife:So how do I write in Json?
老婆:那我怎么用Json写呢?
A good way would be to use a json serialiser - which is a library which does the heavy lifting for you.
一个好方法是使用 json 序列化器 - 这是一个为您完成繁重工作的库。
Summary
概括
JSON is basically a way of communicating data to someone, with very, very specific rules. Using Key Value Pairs and Arrays.This is the concept explained, at this point it is worth reading the specific rules above.
JSON 基本上是一种将数据传达给某人的方式,具有非常非常具体的规则。使用键值对和数组。这就是概念的解释,在这一点上值得阅读上面的具体规则。
回答by Vilx-
In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:
简而言之 - JSON 是一种以这种方式进行序列化的方式,它变成了 JavaScript 代码。执行时(使用 eval 或其他方式),此代码创建并返回一个 JavaScript 对象,其中包含您序列化的数据。这是可用的,因为 JavaScript 允许以下语法:
var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
var MyObject = {
'StringProperty' : 'Value',
'IntProperty' : 12,
'ArrayProperty' : [ 1, 2, 3],
'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
}; // MyObject is now an object with property values set.
You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.
您可以将其用于多种目的。首先,这是一种将数据从服务器后端传递到 JavaScript 代码的舒适方式。因此,这在 AJAX 中经常使用。
You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.
您还可以将其用作独立的序列化机制,它比 XML 更简单,占用的空间更少。有许多库允许您针对各种编程语言对 JSON 中的对象进行序列化和反序列化。
回答by mson
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
简而言之,它是一种用于传递数据的脚本符号。在某些方面,XML 的替代品,本机支持基本数据类型、数组和关联数组(名称-值对,称为对象,因为这就是它们所代表的内容)。
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
语法是 JavaScript 中使用的语法,JSON 本身代表“JavaScript Object Notation”。然而,它已经变得可移植并且也被用于其他语言。
A useful link for detail is here:
一个有用的详细链接在这里:
回答by Pinakin Nayi
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
JSON 格式通常用于通过网络连接序列化和传输结构化数据。它主要用于在服务器和 Web 应用程序之间传输数据,作为 XML 的替代方案。
回答by Nolte
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
JSON 是 JavaScript 对象表示法。与 XML 相比,它是一种更紧凑的跨网络连接传输数据集的方式。我建议在任何类似 AJAX 的应用程序中使用 JSON,否则 XML 将是“推荐”选项。XML 的冗长会增加下载时间并增加带宽消耗 ($$$)。您可以使用 JSON 实现相同的效果,它的标记几乎专门用于数据本身,而不是底层结构。
回答by Steven A. Lowe
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
常见的简短回答是:如果您使用 AJAX 进行数据请求,您可以轻松地将对象作为 JSON 字符串发送和返回。可用的 Javascript 扩展支持对所有 javascript 类型的 toJSON() 调用,以便在 AJAX 请求中将数据发送到服务器。AJAX 响应可以将对象作为 JSON 字符串返回,这些对象可以通过简单的 eval 调用转换为 Javascript 对象,例如,如果 AJAX 函数 someAjaxFunctionCallReturningJson 返回
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
你可以用Javascript编写
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
JSON 也可用于 Web 服务负载等,但它对于 AJAX 结果来说确实很方便。
- Update (ten years later): Don't do this, use JSON.parse
- 更新(十年后):不要这样做,使用 JSON.parse
回答by Jason Baker
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
我喜欢 JSON 主要是因为它非常简洁。对于可以 gzip 压缩的 Web 内容,这不一定是什么大问题(因此xhtml 如此受欢迎)。但在某些情况下,这可能是有益的。
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
例如,对于一个项目,我正在传输需要通过XMPP进行序列化和传输的信息。由于大多数服务器会限制您可以在单个消息中传输的数据量,因此我发现使用 JSON 而不是明显的替代方案 XML 会有所帮助。
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
作为额外的好处,如果您熟悉 Python 或 Javascript,那么您已经非常了解 JSON 并且无需太多培训就可以解释它。
回答by Elangovan
What is JSON?
什么是 JSON?
JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript.
JavaScript Object Notation (JSON) 是一种受 JavaScript 对象字面量启发的轻量级数据交换格式。
JSON values can consist of:
JSON 值可以包括:
objects (collections of name-value pairs) arrays (ordered lists of values) strings (in double quotes) numbers true, false, or null
对象(名称-值对的集合) 数组(有序的值列表) 字符串(双引号) 数字 true、false 或 null
JSON is language independent.
JSON 与语言无关。
JSON with PHP?
JSON 与 PHP?
After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.
PHP 5.2.0 之后,JSON 扩展默认为解码和编码功能。
Json_encode - returns the JSON representation of values Json_decode - Decodes the JSON String Json_last_error - Returns the last error occured.
Json_encode - 返回值的 JSON 表示 Json_decode - 解码 JSON 字符串 Json_last_error - 返回最后发生的错误。
JSON Syntax and Rules?
JSON 语法和规则?
JSON syntax is derived from JavaScript object notation syntax:
JSON 语法源自 JavaScript 对象符号语法:
Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays
数据在名称/值对中 数据以逗号分隔 花括号保存对象 方括号保存数组
回答by Ganesh Vellanki
The difference between JSON and conventional syntax would be as follows (in Javascript)
JSON 和传统语法之间的区别如下(在 Javascript 中)
Conventional
传统的
function Employee(name, Id, Phone, email){
this.name = name;
this.Id = Id;
this.Phone = Phone;
this.email = email;
}
//access or call it as
var Emp = new Employee("mike","123","9373849784","[email protected]");
With JSON
使用 JSON
if we use JSON we can define in different way as
如果我们使用 JSON,我们可以用不同的方式定义为
function Employee(args){
this.name = args.name;
this.Id = args.Id;
this.Phone = args.Phone;
this.email = args.email;
}
//now access this as...
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});
The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.
我们必须记住的重要一点是,如果我们必须在没有 JSON 方法的情况下构建具有 100 个元素的“Employee”类或模态,我们必须在创建类时解析所有内容。但是使用 JSON 我们只能在定义类的新对象时内联定义对象。
so this line below is the way of doing things with JSON(just a simple way to define things)
所以下面这行是用 JSON 做事的方式(只是一种简单的定义方式)
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});


