简体   繁体   中英

Why is JSON important?

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?

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.

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

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

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

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

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM