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.