为什么每个人都为 jQuery 选择 JSON 而不是 XML?

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

Why is Everyone Choosing JSON Over XML for jQuery?

jqueryxmljson

提问by Luke101

I thought XML is highly portable and can be used as a mini database. I have seen XML used everywhere. I even see large companies switching over to JSON. Even Microsoft has integrated support for JSON. What is all the hype over JSON?

我认为 XML 具有高度的可移植性,可以用作小型数据库。我见过到处都在使用 XML。我什至看到大公司转向JSON。甚至 Microsoft 也集成了对 JSON 的支持。关于 JSON 的所有炒作是什么?

回答by CMS

Basically because JSON is recognized natively by JavaScript, it's really lightweight, minimalistic and highly portable because it relies only on two fundamental structures:

基本上是因为 JSON 被 JavaScript 本地识别,它非常轻量级、简约且高度可移植,因为它只依赖于两个基本结构:

  • 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.
  • 名称/值对的集合。在各种语言中,这被实现为对象、记录、结构、字典、哈希表、键控列表或关联数组。
  • 值的有序列表。在大多数语言中,这被实现为数组、向量、列表或序列。

回答by jcdyer

XML doesn't really begin to shine until you start mixing together different namespaced schemas. Then you see JSON start to fall down, but if you just need a serialization format for your data, JSON is smaller, lighterweight, more human readable, and generally faster than XML.

直到您开始将不同的命名空间模式混合在一起,XML 才真正开始发挥作用。然后您会看到 JSON 开始下降,但是如果您只需要数据的序列化格式,那么 JSON 更小、更轻、更易读,而且通常比 XML 更快。

回答by user210794

I find that a big benefit of JSON over XML is that I don't have to decide how to format the data. As some have shown, there are numerous ways to do even simple data structures in XML -- as elements, as attribute values, etc. Then you have to document it, write up XML Schema or Relax NG or some other crap... It's a mess.

我发现 JSON 相对于 XML 的一大好处是我不必决定如何格式化数据。正如一些人所展示的,在 XML 中,即使是简单的数据结构,也有很多方法——作为元素、作为属性值等。然后你必须记录它,写下 XML 模式或放松 NG 或其他一些废话......它是一团糟。

XML may have its merits, but for basic data interchange, JSON is much more compact and direct. As a Python developer, there is no impedance mismatch between the simple data types in JSON and in Python. So if I was writing a server-side handler for an AJAX query that was asking about snow conditions for a particular Ski resort, I would build up a dictionary like follows:

XML 可能有其优点,但对于基本数据交换,JSON 更加紧凑和直接。作为 Python 开发人员,JSON 和 Python 中的简单数据类型之间没有阻抗失配。因此,如果我正在为 AJAX 查询编写服务器端处理程序,该查询询问特定滑雪胜地的雪况,我将构建如下字典:

conditions = {
    'new_snow_24': 5.0,
    'new_snow_48': 8.5,
    'base_depth': 88.0,
    'comments': 'Deep and steep!',
    'chains_required': True,
}
return simplejson.dumps(conditions)   # Encode and dump `conditions` as a JSON string

When translated through JSON (using a library like 'simplejson' for Python), the resulting JSON structure looks nearly identical (except in JSON, booleans are lower-cased).

当通过 JSON 转换时(使用像 Python 的“simplejson”这样的库),生成的 JSON 结构看起来几乎相同(除了在 JSON 中,布尔值是小写的)。

Decoding that structure only requires a JSON parser, whether it's for Javascript or Objective-C for a native iPhone app or C# or a Python client. The floats would get interpreted as floats, the strings as strings, and booleans as booleans. Using the 'simplejson' library in Python, a simplejson.loads(some_json_string)statement would give me back a full data structure like I just made in the above example.

解码该结构只需要一个 JSON 解析器,无论是用于 Javascript 或 Objective-C 的原生 iPhone 应用程序,还是 C# 或 Python 客户端。浮点数会被解释为浮点数,字符串会被解释为字符串,布尔值会被解释为布尔值。在 Python 中使用 'simplejson' 库,一个simplejson.loads(some_json_string)语句会给我一个完整的数据结构,就像我在上面的例子中所做的那样。

If I wrote XML, I'd have to decide whether to do elements or attributes. Both of the following are valid:

如果我写 XML,我必须决定是做元素还是属性。以下两项均有效:

<conditions>
    <new-snow-24>5</new-snow-24>
    <new-snow-48>8.5</new-snow-48>
    <chains-required>yes</chains-required>
    <comments>deep and steep!</comments>
</conditions>

<conditions newSnow24="5" newSnow48="8.5" chainsRequired="yes">
   <comments>deep and steep!</comments>
</conditions>

So not only do I have to think about the data that I may want to send to the client, I have to think about how to format it. XML, while simpler than plain SGML by being more strict with its rules, still provides too many ways to think about that data. Then I would have to go about generating it. I could not just take a Python dictionary (or other simple data structure) and say "go make thyself into my XML". I could not receive an XML document and immediately say "go make thyself into objects and data structures" without writing a custom parser, or without requiring the additional overhead of XML Schema/Relax NG and other such pains.

因此,我不仅要考虑可能要发送给客户端的数据,还必须考虑如何对其进行格式化。XML 虽然比普通 SGML 更简单,因为它的规则更严格,但仍然提供了太多的方式来考虑该数据。然后我将不得不去生成它。我不能只拿 Python 字典(或其他简单的数据结构)说“去把你自己变成我的 XML”。我无法在不编写自定义解析器的情况下收到 XML 文档并立即说“将自己变成对象和数据结构”,或者不需要 XML Schema/Relax NG 和其他此类痛苦的额外开销。

The short of it is that it's just much easier and much more direct to encode and decode data to JSON, especially for quick interchanges. This may apply more to people coming from a dynamic language background, as the basic data types (lists, dictionaries, etc) built in to JavaScript / JSON directly map to the same or similar data types in Python, Perl, Ruby, etc.

简而言之,将数据编码和解码为 JSON 更容易、更直接,尤其是对于快速交换。这可能更适用于来自动态语言背景的人,因为 JavaScript / JSON 中内置的基本数据类型(列表、字典等)直接映射到 Python、Perl、Ruby 等中相同或相似的数据类型。

回答by avatar

The performance of JSON isn't much different from XML for most use cases, JSON isn't well suited and readable for deeply nest structures... you will run into ]]]}], which makes debugging difficult

对于大多数用例,JSON 的性能与 XML 没有太大区别,JSON 不太适合深度嵌套结构且可读性不佳……您会遇到 ]]]}],这使得调试变得困难

回答by Ron Gejman

It's lightweight compared to XML. If you need to scale, reduce your bandwidth requirements!

与 XML 相比,它是轻量级的。如果您需要扩展,请降低带宽要求!

Compare JSON

比较 JSON

 [
      {
           color: "red",
           value: "#f00"
      },
      {
           color: "green",
           value: "#0f0"
      },
      {
           color: "blue",
           value: "#00f"
      },
      {
           color: "cyan",
           value: "#0ff"
      },
      {
           color: "magenta",
           value: "#f0f"
      },
      {
           color: "yellow",
           value: "#ff0"
      },
      {
           color: "black",
           value: "#000"
      }
 ]

to XML:

到 XML:

 <colors>
      <color >
           <name>red</name>
           <value>#f00</value>
      </color>
      <color >
           <name>green</name>
           <value>#0f0</value>
      </color>
      <color >
           <name>blue</name>
           <value>#00f</value>
      </color>
      <color >
           <name>cyan</name>
           <value>#0ff</value>
      </color>
      <color >
           <name>magenta</name>
           <value>#f0f</value>
      </color>
      <color >
           <name>yellow</name>
           <value>#ff0</value>
      </color>
      <color >
           <name>black</name>
           <value>#000</value>
      </color>
 </colors>

回答by Nate B

Just an anecdote from my own personal experience:

仅从我个人的经历中讲一个轶事:

I wrote a small Javascript directory, first with the data in XML, and then adapted it to use JSON so I could run them side-by-side and compare speeds with Firebug. The JSON ended up being approximately 3 times faster (350-400 ms vs. 1200-1300 ms to display all data). Also, as others have noted, the JSON is much easier on the eyes and the file size was a good 25% smaller due to the leaner markup.

我编写了一个小的 Javascript 目录,首先使用 XML 中的数据,然后将其调整为使用 JSON,这样我就可以并排运行它们并与 Firebug 比较速度。JSON 最终大约快了 3 倍(350-400 毫秒与 1200-1300 毫秒显示所有数据)。此外,正如其他人所指出的,JSON 看起来更容易,而且由于更精简的标记,文件大小也小了 25%。

回答by Marc

 <colors>
      <color name='red'     value='#f00'/>
      <color name='green'   value='#0f0'/>
      <color name='blue'    value='#00f'/>
      <color name='cyan'    value='#0ff'/>
      <color name='magenta' value='#f0f'/>
      <color name='yellow'  value='#ff0'/>
      <color name='black'   value='#000'/>
 </colors>

With attributes, XML is nice. But for some reason, home-made XML is generally 100% made of elements, and ugly.

对于属性,XML 很好。但是出于某种原因,自制的 XML 通常是 100% 由元素组成的,而且很丑。

回答by Xinus

Easy consumption by JavaScript can be one of the reasons ..

JavaScript 易于使用可能是原因之一..

回答by Joy Dutta

JSON is best for consumption of data in web applications from webservices for its size and ease of use, especially due to the built-in support in JavaScript. Imagine the computation overhead for parsing an xml fragment compared to the instant lookup in JSON.

JSON 最适合从 Web 服务使用 Web 应用程序中的数据,因为它的大小和易用性,特别是由于JavaScript 中的内置支持。想象一下与 JSON 中的即时查找相比,解析 xml 片段的计算开销。

A very good example is JSON-P. You can get back data from a webservice wrapped in a callback function call, like my_callback({"color": "blue", "shape":"square"});inside a dynamically generated <script>tag so the data can be directly consumed in the function my_callback(). There is no way to get even close to this convenience using XML.

一个很好的例子是 JSON-P。您可以从包含在回调函数调用中的 Web 服务取回数据,就像my_callback({"color": "blue", "shape":"square"});在动态生成的<script>标签中一样,这样数据就可以直接在函数中使用my_callback()。使用 XML 无法接近这种便利。

XML would be the format of choice for large documents, where you have a framework of rendering pages of data in multiple formats using XSLT. XML can also be used with application configuration files for readability among many other uses.

XML 将是大型文档的首选格式,其中您有一个使用 XSLT 以多种格式呈现数据页面的框架。XML 还可以与应用程序配置文件一起使用,以便在许多其他用途中提高可读性。

回答by A.P.

No one here has mentioned XML-s main advantage: validation rules (DTD, XSD). My conclusions, having used both:

这里没有人提到 XML-s 的主要优点:验证规则(DTD、XSD)。我的结论,同时使用了两者:

  • JSON is perfect for ajax, especially if you develop both server and client side yourself. You basically create js objects right in your server script!
  • XML shines in corporate environments, when you have to set data exchange standards between big bureaucratic organizations. Often, one party develops its part months before another, so it really benefits from validating its requests against agreed XSD. Also, in big corporations, data transfer is often translated between different systems. This is also XML's strength, think XSLT. Example: code-free conversion into JSON :p
  • JSON 非常适合 ajax,特别是如果您自己开发服务器端和客户端。您基本上可以在服务器脚本中创建 js 对象!
  • 当您必须在大型官僚组织之间设置数据交换标准时,XML 在企业环境中大放异彩。通常,一方比另一方提前几个月开发其部分,因此它确实受益于针对商定的 XSD 验证其请求。此外,在大公司中,数据传输通常在不同系统之间进行转换。这也是 XML 的强项,想想 XSLT。示例:无代码转换为 JSON :p

Of course, there's json-schema being developed but you won't find built-in support for it anywhere.

当然,有 json-schema 正在开发中,但您不会在任何地方找到对它的内置支持。

I'm a fanboy of both, they have just different strengths.

我是两者的粉丝,他们只是有不同的优势。