views:

1313

answers:

11

I've only recently heard about JSON (Javascript Object Notation). Can anybody explain why it is considered (by some websites/blogs/etc) to be important? We already have XML, why is JSON better (apart from being 'native to Javascript')?

Edit: Hmm, the main answer theme seems to be 'it is smaller'. However, the fact that it allows data fetching across domains, seems important to me. Or is this in practice not (yet) much used?

A: 

It's not that it is better, but that it can tie many things together to allow seamless data transfer without manual parsing!

For example javascript -> C# web service -> javascript

Stevo3000
I don't think that counts as an argument considering that even in JavaScript often the JSON is not eval'd but parsed for security reasons.
Benedikt Eger
@Benedikt Eger - There is a new replacement for eval coming that will evaluate JSON without the risks of eval. Plus if the JSON is coming from a trusted source it will normally be eval'd.
Stevo3000
+11  A: 

JSON is generally much smaller than its XML equivalent. Smaller transfer means faster transfer, which results in a better user experience.

Richard Szalay
I don't agree that json is smaller. `<person name='John Doe' tags='friend male'/>` is the compact XML format. 44 chars. The compact json is: `{person:{"name":"John Doe","tag":["friend","male"]}}` 52 chars. There's a 25% difference, in favor of XML. XML *can* be larger, but need not be so.
Cheeso
I agree, hence my use of the word "generally". Once you have arrays of complex items, XML becomes larger than JSON. Surely your misreading of the word "generally" isn't worth a downvote?
Richard Szalay
Your compact JSON is incorrect, it should be `{"name":"John Doe","tag":["friend","male"]}`. This makes it 45 characters, which is still larger than the XML but only by 1 character.
Richard Szalay
+1  A: 

Rabarberski,

This will show why it is important/better than XML:

http://www.json.org/fatfree.html

RichardOD
+4  A: 

These web pages may help:

  1. JSON - The Fat Free alternative to xml
  2. Why JSON is Important to You!
Sam Meldrum
From the second link "If the data is formatted as XML then Ajax is limited to fetching data from the same domain (website) that the Ajax application came from. If the data is formatted as JSON then Ajax can travel across domains"That's not right, is it ?
Brian Agnew
Brian, I think you're right. Suggest second link is treated as suspect - it just seemed to answer the question in its mission even though it fails to achieve it in places.
Sam Meldrum
@Sam. Fair enough. Thx.
Brian Agnew
It's partially right. I believe using JSONp you can travel across domains in Firefox.
cdmckay
+17  A: 

XML has several drawbacks:

  • It's heavy!
  • It provides a hierarchical representation of content which is not exactly the same as (but pretty much similar to) Javascript object model.
  • Javascript is available everywhere. Without any external parsers, you can process JSONs directly with JS interpreter.

Clearly it's not meant to replace XML completely. For JS based Web apps, its advantages can be useful.

Mehrdad Afshari
What do you mean by 'Javascript is available everywhere' ? If I interface my Java application to a CouchDb instance, I have XML parsers natively available, but no Javascript parser.
Brian Agnew
Everywhere in this sense means "on every computer (with a modern browser)."
Mehrdad Afshari
@Rabarberski: Being the exact same object model is also a huge advantage that might be undervalued sometimes.
Mehrdad Afshari
@Mehrdad. Note my example above - Java/CouchDb doesn't involve a browser
Brian Agnew
I agree. As I said it was an exaggeration. I mean from a Web app perspective, it's available on roughly every client.
Mehrdad Afshari
@Brian Agnew: there are JSON parsers libraries for nearly every language out there. Check near the bottom of the http://json.org/ page (a majority of them are written in Java).
barkmadley
The heaviness is a misnomer. It's really not significantly different than XML, and in simple cases XML can be smaller. In any case, size is not a clear distinguishing factor. The ubiquity is also not a clear factor. The only thing that remains is the javascript friendliness, the ability to `eval()` received json in a browser app. This is the differentiator and the one thing above all else that has powered adoption of json.
Cheeso
@Cheeso - `eval()` is also recommended against, since it can lead to XSS attacks.
Richard Szalay
+9  A: 

JSON is much more concise. XML:

<person>
    <name>John Doe</name>
    <tags>
        <tag>friend</tag>
        <tag>male</tag>
   </tags>
</person>

JSON:

{"name": "John Doe", "tags": ["friend", "male"]}

There's fewer overlapping features, too. For example, in XML there's tension between choosing to use elements (as above), versus attributes (<person name="John Doe">).

jmah
I actually find XML much easier to read.
Steve Harrison
Ignoring extraneous whitespace, that's roughly 44 characters vs 78 but bear in mind that any single child element like name can be replaced with an attribute (saving another 7 or so characters).
cletus
@Steve, since when was readability important on data interchange formats?
J-P
@JimmyP: Point taken.
Steve Harrison
@Steve: Well formatted for humans (as would be desirable when used for config), JSON is both much easier to read and more compact than XML.
Software Monkey
I think readability can be very important, but you can format the JSON with tags and line breaks to match the xml.
Joel Coehoorn
I don't agree that json is smaller. `<person name='John Doe' tags='friend male'/>` is the compact XML format. 44 chars. The compact json is: `{person:{"name":"John Doe","tag":["friend","male"]}}` 52 chars. There's a 25% difference, in favor of XML. XML *can* be larger, but need not be so.
Cheeso
+1  A: 

JSON is a way to serialize data in Javascript objects. The syntax is taken from the language, so it should be familiar to the developer dealing with Javascript, and -- being the stringification of an object -- it's a more-natural serialization method for interaction within the browser than a full-fledged XML derivative (with all the arbitrary design decisions that implies).

It's light and intuitive.

Anonymous
+10  A: 

JSON came into popular use primarily because it offers a way to circumvent the same-origin policy used in web browsers and thereby allow mashups.

Let's say you're writing a web service on domain A. You can't load XML data from domain B and parse it because the only way to do that would be XMLHttpRequest, and XMLHttpRequest was originally limited by the same-origin policy to talking to only URLs at the same domain as the containing page.

It turns out that for a variety of reasons, you are allowed to request <script> tags across origins. Clever people realized this was a good way to work around the limitation with XMLHttpRequest. Instead of the server returning XML, it can return a series of JavaScript object and array literals.

(bonus question left as an exercise to the reader: why is <script src="..."> allowed across domains without server opt-in but XHR isn't?)

Of course, returning a <script> which consists of nothing more than object literals is not useful because without assigning the values to some variable, you can't do anything with it. Thus, most services use a variant of JSON, called JSONP (http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/).

With the rise in popularity of mashups, people realized that JSON was a convenient data interchange format in general, especially when JavaScript is one end of the channel. For example, JSON is used extensively in Chromium, even in cases where C++ is on both sides. It's just a nice lightweight way to represent simple data, that good parsers exist for in many languages.

Amusingly, using <script> tags to do mashups is incredibly insecure because it is essentially XSS'ing yourself on purpose. So native JSON (http://ejohn.org/blog/native-json-support-is-required/) had to be introduced, which obviates the original benefits of the format. But by that time, it was already super popular :)

Aaron Boodman
I don't understand this origin story. It's trivial to write a JavaScript function that returns an (unparsed) XML document. You could use this hack to provide XML just as easily as using it to provide an entirely new serialization format.
Robert Rossney
It's true, you could just return a string of XML and then parse it. But the string would have to be carefully escaped inside a JavaScript string. People found themselves dynamically generating:returnData("<data foo=\"bar\">...</foo>")... and asking themselves why bother when they could just return objects and arrays directly.And once you go down that path, you realize that working with native objects and arrays with no separate parse phase is just a better idea in general. But I think that mashups are how JSON got started, or at least one of a couple primary reasons.
Aaron Boodman
+2  A: 

It depends on what you are going to do. There are a lot of answers here that prefer JSON over XML. If you take a deeper look there isn't a big difference.

If you have a tree of objects you get only tree of javascript objects back. If you take a look at the tension to use OOP style access than turns back on you. Assume you have an object of type A, B ,C that are constructed in a tree. You can easily enable them to be serialzed to JSON. If you read them back in you only get a tree of javascript objects. To reconstruct your A, B, C you have to stuff the values manually into manually created objects or you doing some hacks. Sound like parsing XML and creating objects? Well, yes :)

This days only the newest browsers come with native support for JSON. To support more browsers you have two options: a) you load a json paraser in javascript that helps you parsing. So, how fat does this sound regarding fatreeness? The other option as I often see is eval. You can just do eval() on a JSON String to get the objects. But that introduces a whole new set of security problems. JSON is specified so it can't contain functions. If you are not checking the objects for function someone can easily send you code that is being executed.

So it might depend on what you like more: JSON or XML. The biggest difference is propably the ways of accessing things, be it script tags XMLHTTPRequest... I would decide upon this what to use. In my opinion if there would be proper support for XPATH in the browsers I would often decide for XML to use. But the fashion is directed towards json and loading additional json parsers in javascript.

If you can't decide and you know you need something really powerful you ight have to take a look at YAML. Reading about YAML is very interesting to get more insight in the topic. But it really depends on what you are trying to do.

Norbert Hartl
+1  A: 

JSON's a text-based object serialization format that's more lightweight than XML and that directly integrates with JavaScript's object model. That's most of its advantages right there.

Its disadvantages (compared to XML) are, roughly: fewer available tools (forget about standard validation and/or transformation, to say nothing of syntax highlighting or well-formedness checking in most editors), less likely to be human-readable (there's huge variations in the readability of both JSON and XML, so that's a necessarily fuzzy statement), tight integration with JavaScript makes for not-so-tight integration with other environments.

Robert Rossney
+5  A: 

If you are working in Javascript, it is much easier to us JSON. This is because JSON can be directly evaluated into a Javascript object, which is much easier to work with than the DOM.

Borrowing and slightly altering the XML and JSON from above

XML:

<person>
    <name>John Doe</name>
    <tag>friend</tag>
    <tag>male</tag>
</person>

JSON:

{ person: {"name": "John Doe", "tag": ["friend", "male"]} }

If you wanted to get the second tag object with XML, you'd need to use the powerful but verbose DOM apis:

var tag2=xmlObj.getElementsByTagName("person")[0].getElementsByTagName("tag")[1];

Whereas with a Javascript object that came in via JSON, you could simply use:

var tag2=jsonObj.person.tag[1];

Of course, Jquery makes the DOM example much simpler:

var tag2=$("person tag",xmlObj).get(1);

However, JSON just "fits" in a Javascript world. If you work with it for a while, you will find that you have much less mental overhead than involving XML based data.

All the above examples ignore the possibility that one or more nodes are available, duplicated, or the possibility that the node has just one or no children. However, to illustrate the native-ness of JSON, to do this with the jsonObj, you'd just have to:

var tag2=(jsonObj.person && jsonObj.person.tags && jsonObj.person.tags.sort && jsonObj.person.tags.length==2 ? jsonObj.person.tags[1] : null);

(some people might not like that long of ternary, but it works). But XML would be (in my opinion) nastier (I don't think you'd want to go the ternary approach because you'd keep calling the dom methods which may have to do the work over again depending on implementation):

var tag2=null;
var persons=xmlObj.getElementsByTagName("person");
if(persons.length==1) {
    var tags=persons[0].getElementsByTagName("tag");
    if(tags.length==2) { tag2=tags[1]; }
}

Jquery (untested):

var tag2=$("person:only-child tag:nth-child(1)",xmlObj).get(0);
larson4