JSON 和 XML 比较

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

JSON and XML comparison

xmljson

提问by Durga Dutt

I want to know which is faster: XML and JSON? When to use which one ?

我想知道哪个更快:XML 和 JSON?什么时候用哪一种?

采纳答案by jelford

Before answering when to use which one, a little background:

在回答什么时候用哪个之前,先来个背景:

edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format hasto be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

编辑:我应该提到这种比较实际上是从在带有 JavaScript 的浏览器中使用它们的角度来看的。这也不数据格式的方法被使用,并且有很多很好的解析器,这将改变细节,使我在说什么不是很有效的。

JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.

JSON 更紧凑,(在我看来)更易读——在传输中它可以“更快”,因为传输的数据更少。

In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemasdisambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

在解析中,这取决于您的解析器。将代码(无论是 JSON 还是 XML)转换为数据结构(如地图)的解析器可能会受益于 XML 的严格性质(XML 模式很好地消除了数据结构的歧义)——但是在 JSON 中,项目的类型(字符串/数字/嵌套 JSON 对象)可以在语法上推断,例如:

myJSON = {"age" : 12,
          "name" : "Danielle"}

The parser doesn't need to be intelligent enough to realise that 12represents a number, (and Danielleis a string like any other). So in javascript we can do:

解析器不需要足够智能来意识到它12代表一个数字(并且Danielle是一个像任何其他字符串一样的字符串)。所以在javascript中我们可以这样做:

anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False

In XML we'd have to do something like the following:

在 XML 中,我们必须执行以下操作:

<person>
    <age>12</age>
    <name>Danielle</name>
</person>

(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:

(顺便说一句,这说明了 XML 更为冗长的观点;这是对数据传输的关注)。要使用这些数据,我们将通过解析器运行它,然后我们必须调用类似的东西:

myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True

Actually, a good parser might well type the agefor you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name. It might be more intuitive to form the XML like this:

实际上,一个好的解析器很可能会age为您键入(另一方面,您可能不希望它这样做)。当我们访问这些数据时发生了什么 - 而不是像上面的 JSON 示例中那样进行属性查找 - 我们正在对 key 进行映射查找name。像这样形成 XML 可能更直观:

<person name="Danielle" age="12" />

But we'd still have to do map lookups to access our data:

但是我们仍然需要进行地图查找才能访问我们的数据:

myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");

EDIT: Original:

编辑:原文:

In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).

在大多数编程语言中(并非全部,无论如何),像这样的地图查找将比属性查找(就像我们上面解析 JSON 时得到的那样)成本更高。

This is misleading: remember that in JavaScript (and other dynamic languages) there's no differencebetween a map lookup and a field lookup. In fact, a field lookup isjust a map lookup.

这是一种误导:请记住,在 JavaScript(和其他动态语言)中,地图查找和字段查找之间没有区别。事实上,现场查找只是一个地图查找。

If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.

如果您想要进行真正有价值的比较,最好对其进行基准测试 - 在您计划使用数据的上下文中进行基准测试。

As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.

在我打字的时候,Felix Kling 已经给出了一个相当简洁的答案,比较了它们的使用时间,所以我不会再继续下去了。

回答by Felix Kling

Fasteris not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.

更快不是 JSON 或 XML 的属性,也不是它们之间的比较会产生的结果。如果有,那么它是解析器的属性或传输数据的带宽。

Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:

这是(开头)JSON 和 XML 的优缺点列表:



JSON

JSON

Pro:

亲:

  • Simple syntax, which results in less "markup" overhead compared to XML.
  • Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.
  • JSON Schemafor description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures
  • 语法简单,与 XML 相比,“标记”开销更少。
  • 易于与 JavaScript 一起使用,因为标记是 JS 对象文字符号的子集,并且具有与 JavaScript 相同的基本数据类型。
  • 用于描述和数据类型和结构验证的JSON 模式
  • JsonPath 用于提取深度嵌套结构中的信息

Con:

骗局:

  • Simple syntax, only a handful of different data types are supported.

  • No support for comments.

  • 语法简单,只支持少数不同的数据类型。

  • 不支持评论。



XML

XML

Pro:

亲:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schemafor datatype, structure validation. Makes it also possible to create new datatypes
  • XSLTfor transformation into different output formats
  • XPath/XQueryfor extracting information in deeply nested structures
  • built in support for namespaces
  • 通用标记;可以为任何目的创建“方言”
  • 用于数据类型、结构验证的XML 模式。还可以创建新的数据类型
  • 用于转换为不同输出格式的XSLT
  • XPath/ XQuery用于提取深度嵌套结构中的信息
  • 内置对命名空间的支持

Con:

骗局:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).
  • 与 JSON 相比相对冗长(导致相同数量的信息产生更多的数据)。


So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.

所以最后你必须决定你需要什么。显然,这两种格式都有其合法的用例。如果您主要使用 JavaScript,那么您应该使用 JSON。

Please feel free to add pros and cons. I'm not an XML expert ;)

请随意添加优点和缺点。我不是 XML 专家 ;)

回答by Hibou57

Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.

处理速度可能不是唯一相关的问题,但是,因为这是一个问题,所以这里有一些基准测试中的数字:JSON vs. XML:一些关于 verbosity 的硬数字。对于速度,在这个简单的基准测试中,XML 的开销比 JSON 高 21%。

An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.

关于冗长的一个重要说明,正如文章所说,最常见的抱怨是:这在实践中没有那么重要(XML 和 JSON 数据通常都不是由人类处理,而是由机器处理),即使对于速度,它需要一些合理的更多时间来压缩。

Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.

另外,在这个基准测试中,处理了大量的数据,一个典型的 web 应用程序不会传输这样大小的数据块,大到 90MB,压缩可能没有好处(对于足够小的数据块,压缩块将大于未压缩的块),因此不适用。

Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.

尽管如此,如果不涉及压缩,那么显然更简洁的 JSON 在传输通道上的权重将更小,尤其是如果通过 WebSocket 连接传输时,没有经典的 HTTP 开销可能会使 JSON 的优势有所不同,甚至更多重大。

After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.

传输完成后,要消耗数据,这在总处理时间中计入。如果要传输足够大或足够复杂的数据,由于缺少由验证 XML 解析器自动检查的模式,可能需要对 JSON 数据进行更多检查;这些检查必须在 JavaScript 中执行,而 JavaScript 并不是特别快,因此在这种情况下它可能会比 XML 带来额外的开销。

Anyway, only testing will provides the answer for your particular use?case(if speed is really the only matter, and not standard nor safety nor integrity…).

无论如何,只有测试才能为您的特定用例提供答案?(如果速度真的是唯一的问题,而不是标准、安全或完整性……)。

Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.

更新 1:值得一提的是 EXI,二进制 XML 格式,它以比使用 Gzip 更低的成本提供压缩,并节省了解压缩压缩 XML 所需的处理。EXI 之于 XML,BSON 之于 JSON。这里有一个快速概述,参考空间和时间的效率:EXI:最后一个二进制标准?.

Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.

更新 2:还有一个二进制 XML 性能报告,由 W3C 进行,因为效率和低内存和 CPU 占用,也是 XML 领域的问题:高效 XML 交换评估

Update 2015-03-01

更新 2015-03-01

Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Codingfor the HTTP protocol (alongside with compress, deflateand gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters?(iana.org).

在这种情况下值得注意,因为 HTTP 开销被提出作为一个问题:IANA 已注册 EXI 编码(上面提到的高效二进制 XML),作为HTTP 协议的内容编码(以及compressdeflategzip) . 这意味着 EXI 是一个可以被浏览器和可能的其他 HTTP 客户端理解的选项。请参阅超文本传输​​协议参数?(iana.org)

回答by Christian Vielma

I found this article at digital bazaarreally interesting. Quoting their quotations from Norm:

在数字集市上发现这篇文章非常有趣。引用他们从 Norm 的报价:

About JSON pros:

关于 JSON 专家:

If all you want to pass around are atomic values or lists or hashes of atomic values, JSON has many of the advantages of XML: it's straightforwardly usable over the Internet, supports a wide variety of applications, it's easy to write programs to process JSON, it has few optional features, it's human-legible and reasonably clear, its design is formal and concise, JSON documents are easy to create, and it uses Unicode. ...

如果您只想传递原子值或原子值的列表或散列,那么 JSON 具有 XML 的许多优点:它可以直接在 Internet 上使用,支持多种应用程序,很容易编写程序来处理 JSON,它几乎没有可选功能,易于阅读且相当清晰,其设计形式简洁,JSON 文档易于创建,并且使用 Unicode。...

About XML pros:

关于 XML 优点:

XML deals remarkably well with the full richness of unstructured data. I'm not worried about the future of XML at all even if its death is gleefully celebrated by a cadre of web API designers.

And I can't resist tucking an "I told you so!" token away in my desk. I look forward to seeing what the JSON folks do when they are asked to develop richer APIs. When they want to exchange less well strucured data, will they shoehorn it into JSON? I see occasional mentions of a schema language for JSON, will other languages follow? ...

XML 处理非结构化数据的全部丰富性非常好。我一点也不担心 XML 的未来,即使它的死亡被一群 Web API 设计人员欢欣鼓舞。

我无法抗拒塞进一句“我早就告诉过你了!” 记号在我的办公桌上。我期待看到 JSON 人在被要求开发更丰富的 API 时会做些什么。当他们想要交换结构不太好的数据时,他们会将其硬塞到 JSON 中吗?我偶尔会看到 JSON 的模式语言,其他语言会跟进吗?...

I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)

我个人同意规范。我认为对 XML 的大多数攻击来自针对典型应用程序的 Web 开发人员,而不是真正来自集成开发人员。但这是我的意见!;)

回答by Gergely Fehérvári

The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

XML(可扩展标记语言)经常使用 XHR,因为这是一种标准的广播语言,可以被任何编程语言使用,并且支持服务器端和客户端,因此这是最灵活的解决方案。XML 可以分成更多的部分,这样指定的组就可以开发程序的一部分,而不会影响其他部分。XML 格式也可以由 XML DTD 或 XML Schema (XSL) 确定并且可以进行测试。

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the evalfunction. On the other hand, the evalfunction has got negatives. For example, the program can be very slow parsing JSON and because of security the evalcan be very risky. This not mean that the JSON is not good, just we have to be more careful.

JSON 是一种数据交换格式,作为 JavaScript 应用程序可能的格式越来越流行。基本上这是一个对象符号数组。JSON 的语法非常简单,因此很容易学习。并且 JavaScript 支持使用eval函数解析 JSON 。另一方面,该eval功能有负面影响。例如,程序解析 JSON 的速度可能非常慢,并且出于安全考虑,这eval可能非常危险。这并不意味着 JSON 不好,只是我们必须更加小心。

My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.

我的建议是,您应该将 JSON 用于具有轻量数据交换的应用程序,例如游戏。因为您不必真正关心数据处理,所以这非常简单和快速。

The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.

XML 最适合大型网站,例如购物网站或类似网站。XML 可以更加安全和清晰。您可以创建基本的数据结构和模式来轻松测试更正并将其轻松分成几部分。

I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.

由于速度和安全性,我建议您使用 XML,而对于轻量级的东西,我建议您使用 JSON。

回答by Godfather

The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.

出于安全原因,JSON 的重要之处在于对数据传输进行加密。毫无疑问,JSON 比 XML 快得多。我见过 XML 需要 100 毫秒,而 JSON 只需要 60 毫秒。JSON 数据易于操作。