JSON and XML comparison [closed]
Asked Answered
A

6

283

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

Appendicitis answered 1/2, 2011 at 12:3 Comment(5)
Faster where? Transmission? Processing? Generating? Both have no feet you know. It is likely that JSON is "faster" in some way as it has less markup overhead. On the other side, XML provides XMLSchema to ensure types, structure... so validity. There is XSLT to transform XML in nearly any other output format... It depends on what you need.Tutu
Also check other previously asked questions: stackoverflow.com/search?q=json+vs+xmlTutu
BLARG! This is something I really wanted to know, and was really glad it was here, and the answers were PERFECT . BAD ON YOU, s. e. moderators: maybe it's time to extend your riles of engagement. Good on you for allowing it to be answered, at least!Anchor
I don't care if this post is extremely late to the game, but I agree. If a question is a dupe, irrelevant or in conflict with the terms of service, perhaps (the closed/useless thread) shouldn't be the first thing that comes up in a search. (btw, this is the 2nd [duped] result that comes up) I agree that perhaps answers should be lean and concise but if result after result is a closed, unanswered thread filled with off topic comments (which is against terms of use) then it helps no one.Orphrey
Although the question as asked is unclear, this is NOT an opinion-based question.Amphiprostyle
A
228

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 has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

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

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 Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

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

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

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>

(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:

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

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

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

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.

Anybody answered 1/2, 2011 at 12:3 Comment(7)
Just a pedantic note... A JavaScript field lookup isn't necessarily a map lookup. It depends on the object and the field in question. Small objects (especially those which haven't had properties attached after construction) often used optimized "fast types" with inline caches in modern JS engines, and fall back to slower property bags (map lookups) for objects with a large number of properties or cases where an objects structure is frequently changing.Instant
I find that JSON is easier for humans to parse but XML is easier for computers to parse.Sim
Not true, for example, in PHP, JSON uses json.so with no dependencies at 78k, XML on the other hand, needs the xml.so or xmlreader.so at 54k/32k, but also requires the libxml2.so which 1.4megs. More code makes it takes longer to process and use more memory. Not to mention, XML, because of its nodes/tree structure, has circular references, which can be a pain in any language that doesn't have weak references. I've found in several languages that the XML parser is FAR larger (takes up more memory and uses more memory) than any of their counterpart JSON parsers.Hellkite
Why do you mix JS strict status problem to this unrelated comparison? Referring double or triple equal signs.Poncho
@Poncho because many parsers interpret numerical strings as numbers, or store numbers as numerical strings.Condensed
On the size of JSON and XML -- it’s often quoted as a key point as to why JSON might be preferred. But if we examine the examples you have given here, we find XML has a higher density. For example, if we consider the XML <person name="Danielle" age="12" />, and the equivalent JSON "person": {"age": 12, "name": "Danielle"} then we find the XML has 35 characters and the JSON 41. In this case JSON is more verbose than XML, since in XML we don't need to enclose attribute names in quotes. If in JSON you loose the type name (person) then it is not a direct comparison to the XML.Varsity
continuity.nz/Content/Articles/AuthoringEfficientXML.pdfVarsity
T
258

Faster is 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.

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


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 Schema for description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures

Con:

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

  • No support for comments.


XML

Pro:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schema for datatype, structure validation. Makes it also possible to create new datatypes
  • XSLT for transformation into different output formats
  • XPath/XQuery for extracting information in deeply nested structures
  • built in support for namespaces

Con:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).

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.

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

Tutu answered 1/2, 2011 at 12:3 Comment(9)
Another Con for JSON and Pro for XML: JSON does not support object reference (cyclic or not), XML does. XML does this by forcing the id attribute to be unique within the document.Wenzel
@EarthEngine Actually Json.Net (json.codeplex.com) does support object references: james.newtonking.com/projects/json/help/index.html?topic=html/….Iritis
@DmitryLobanov: They just add some additional restrictions to JSON standard, but it is not recognized by other JSON tools. So it is not "native" for JSON. However for XML, the restriction is written in the standard so it is native.Wenzel
What about JSON Schema? en.wikipedia.org/wiki/JSON#JSON_SchemaDwarfism
JSON have arrays inbuilt, as well as "null" value. Whereas in XML you need some sort of a convention across your schema parsers. There is also XSLT-like conversion projects for JSON (e.g. github.com/emlynoregan/bOTLjs )Register
JSON can have schema validation with JSON schema. JSON path and XSLT equivalent libs are there on github (e.g. JOLT for xslt subset equivalent functionality) Obviously there is less standardizationContracture
Arrays in XML are just element sets. Null is just the absence if an element or attribute.Salaidh
another con for json is, for completeness, that it doesn't support commentsIwo
I see JSON being used as a data exchange format, and talk about regression... developers spend a lot of time "hand-crafting" solutions to deal with: incorrect JSON documents, searching through JSON, transforming it into something else. XML Schema, XPath, and XSLT are huge advantages. The fact that there are efforts here and there to add these to JSON shows this.Counterintelligence
A
228

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 has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

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

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 Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

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

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

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>

(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:

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

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

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

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.

Anybody answered 1/2, 2011 at 12:3 Comment(7)
Just a pedantic note... A JavaScript field lookup isn't necessarily a map lookup. It depends on the object and the field in question. Small objects (especially those which haven't had properties attached after construction) often used optimized "fast types" with inline caches in modern JS engines, and fall back to slower property bags (map lookups) for objects with a large number of properties or cases where an objects structure is frequently changing.Instant
I find that JSON is easier for humans to parse but XML is easier for computers to parse.Sim
Not true, for example, in PHP, JSON uses json.so with no dependencies at 78k, XML on the other hand, needs the xml.so or xmlreader.so at 54k/32k, but also requires the libxml2.so which 1.4megs. More code makes it takes longer to process and use more memory. Not to mention, XML, because of its nodes/tree structure, has circular references, which can be a pain in any language that doesn't have weak references. I've found in several languages that the XML parser is FAR larger (takes up more memory and uses more memory) than any of their counterpart JSON parsers.Hellkite
Why do you mix JS strict status problem to this unrelated comparison? Referring double or triple equal signs.Poncho
@Poncho because many parsers interpret numerical strings as numbers, or store numbers as numerical strings.Condensed
On the size of JSON and XML -- it’s often quoted as a key point as to why JSON might be preferred. But if we examine the examples you have given here, we find XML has a higher density. For example, if we consider the XML <person name="Danielle" age="12" />, and the equivalent JSON "person": {"age": 12, "name": "Danielle"} then we find the XML has 35 characters and the JSON 41. In this case JSON is more verbose than XML, since in XML we don't need to enclose attribute names in quotes. If in JSON you loose the type name (person) then it is not a direct comparison to the XML.Varsity
continuity.nz/Content/Articles/AuthoringEfficientXML.pdfVarsity
T
23

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.

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.

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.

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.

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.

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

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.

Update 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 Coding for the HTTP protocol (alongside with compress, deflate and 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).

Tsana answered 14/8, 2013 at 12:55 Comment(1)
"For the speed, in this simple benchmark, XML presents a 21% overhead over JSON"- there's a vast difference in JSON parsing depending on the specific parser used. It's almost meaningless to quote any particular parser. Same for XML.Gnathic
E
19

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

About JSON pros:

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

About XML pros:

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

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

Ewe answered 20/8, 2013 at 0:42 Comment(1)
Well put! If 80% of active devs are javascript kiddies, 80% will voice their opinion that JSON is "better". But anyone who uses typed languages is just a little amused about JSON. { "foo": 42 } What type is that object? Then, to fix the lack of type, things like this show up: { "__type": "Bar", "foo": 42 }. In XML in contrast type can be connotated to the element name: <Bar><foo>42</foo></Bar>. Only lisp and javascript guys like json ;)Rattish
T
16

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.

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 eval function. On the other hand, the eval function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval can be very risky. This not mean that the JSON is not good, just we have to be more careful.

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.

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.

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

Travelled answered 1/2, 2011 at 12:26 Comment(2)
I'm not downvoting but I am curious how you see JSON as being a heavier payload or slower in general. GZip/Deflate can be applied. It's syntax inherently makes it smaller in terms of bytes. JSON can also define it's schema as a contract and be serialized as such easily.Depend
JSON does not need to be eval'd to be parsed.Common
A
5

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.

Ane answered 16/5, 2013 at 17:16 Comment(3)
I'm agree, JSON wins the battle on data transfer but it lack on markup, validation and extension of the elements. That is why Google crawling sitemap.xml not sitemap.jsonSubaudition
Sitemap was defined before json was popular so that's not the best example. Sitemap is also seen as a server to server where XML is more popular than JSON. (JSON really only because popular because it is easy to work with in JavaScript.)Salaidh
but Google AMP uses json and not xmlKragh

© 2022 - 2024 — McMap. All rights reserved.