我想知道哪个更快:XML和JSON?

推荐答案

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

编辑:我应该提一下,这种比较实际上是从在带有JavaScript的浏览器中使用它们的Angular 进行的.这不是使用数据格式has的方式,而且有很多好的解析器可以改变细节,使我所说的不太有效.

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

在解析时,这取决于您的解析器.将代码(JSON或XML)转换为数据 struct (如映射)的解析器可能受益于XML的严格性质(XML Schemas很好地消除了数据 struct 的歧义)-但是,在JSON中,项的类型(字符串/数字/嵌套的JSON对象)可以从语法上推断出来,例如:

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

解析器不需要足够智能,就可以意识到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:

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

(顺便说一句,这说明了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 age for 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:

<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");

编辑:原创:

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).

这具有误导性:请记住,在JavaScript(和其他动态语言)中,映射查找和字段查找之间只有no difference.事实上,字段查找is仅仅是 map 查找.

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.

Json相关问答推荐

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

Vega通孔信号中的动态梯度

筛选JSON数组以使用Jolt仅保留具有最新日期/时间的条目

替换字符串中特殊字符的Jolt变换

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

Azure数据工厂-WEB活动输出赢得';t返回JSON

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

未知的META规范,无法验证.[规范v1.0.1]

使用 jq 从字符串列表开始创建对象

具有 (RegEx) 模式的 json-schema 中的枚举

为什么解析的字典相等而腌制的字典不相等?

我无法将来自 API 的数据显示到 FlatList 中,但我在 console.log 中看到了它.问题是什么?

JSON Schema 与 XML Schema 的比较及其future

单元测试球衣 Restful Services

如何使用 CORS 实现 JavaScript Google Places API 请求

如何获取json格式的KendoGrid显示数据?

十六进制格式可以与 JSON 文件一起使用吗?如果是这样,怎么做?

JSON.parse 返回字符串而不是对象

如何在 Rails 模型中验证字符串是否为 json

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?