XML and JSON comparisons

Source: Internet
Author: User
Tags cdata xpath

is XML fatter than JSON?

In some cases yes, but not necessarily, compare such fragments:

<age= "All">    <address>        <  name= "Seattle"/>    </address  ></user>

And

{"User": {    "age": $,    "address": {City        : {            name: "Seattle"        }    }}}

The amount of information is almost equal, and XML does not seem redundant. There is an appropriate editor, both of which can have a more beautiful indentation expression.

Of course, there are a lot of things we can see that XML is more than JSON (some say JSON is fat-free alternative to XML), such as XML writing:

<Employees>    <Employee>        <Addressvalue="..."/>    </Employee>    <Employee>        <Addressvalue="..."/>    </Employee>    <Employee>        <Addressvalue="..."/>    </Employee><Employees>

What is the intuitive expression of JSON?

Keep Looking at the example above:

In XML format, I cannot tell that age is actually a number because you cannot further differentiate between simple data types in XML, but JSON is not, 18 is a number, "18″ is a string; True is Boolean true," true "is a string; NULL is null and" null "is a string.

What if you want to express an array? In XML, nodes can be placed under the parent node, whereas JSON has a more intuitive way of [].

If there is a newline character in the string, JSON does not have this problem, and the XML must introduce CDATA to solve the problem, such as:

<script><! [cdata[function  matchwo (b) {if (a < b && a < 0) then  {  /c6>return 1;  } Else   {  return 0;  }]] ></script>

XML also has an advantage

For example, XML can have a declaration (declaration):

<? XML version= ' 1.0 ' encoding= ' character encoding ' standalone= ' yes|no ' ?>

Specifies the encoding format and so on, but JSON has no such thing.

when the above standalone is yes, the DTD is written directly into the XML, so that no additional DTD files are needed, that is, the file is self-explanatory and self-validating. And this, JSON is impossible to do .

In addition, XML can have a namespace, can be introduced through the xmlns attribute different definition files, such as the import of programming language to freely mix, this, JSON is also cannot do:

<h:tablexmlns:h= "http://www.w3.org/TR/html4/">   <H:tr>   <H:TD>Apples</H:TD>   <H:TD>Bananas</H:TD>   </H:tr></h:table>

Also, in the event of accidental formatting errors, the XML checksum is more likely to find "where is wrong" than JSON because of the relationship between the start and end tags, in other words, the likelihood of a fix is greater.

and the mutual transformation between the objects

One of the great benefits of JSON is that some languages can be natively supported, such as JavaScript, which does not require a JSON parser, which means that the object is expressed in JSON format. But the programming language, which supports XML directly, seems to have no, but there are parsers like HTML and other markup languages that can handle any DOM object.

If you want to turn JSON into an object, you can write it in a browser that supports JSON objects:

var obj = json.parse (text);

If this is not supported, you can do this:

var obj = eval ("(" + text + ")");

If this is the reverse, would you like to express the object as a JSON expression?

Json.stringify (obj);

These are native support, and if it is XML, it is much more cumbersome to convert from one object to another, requiring a third-party class library. Supporting the expression of the annotations will make the code much clearer, and the expression of the declarative expression of XML into another class to define declarative expressions, such as this example:

<steplist>  <Step>    <Name>Name1</Name>    <Desc>Desc1</Desc>  </Step>  <Step>    <Name>Name2</Name>    <Desc>Desc2</Desc>  </Step></steplist>

A class with annotations defines declarative expressions:

 [XmlRoot ("Steplist" )]  public  Span style= "color: #0000ff;" >class   steplist{[XmlElement ( "Step" public  list<step> Steps {get; set;}}  public  class   step{[XmlElement ( "Name"  public
       string Name {get; set;} [XmlElement ( Desc ")]  public   

For the conversion between XML and JSON, in addition to the class library, there are some online tools, easy to use, such as this .

XML DTD and JSON Schema

A DTD refers to the document Type definition, which defines the format and meaning of the node attribute of an XML file, such as a DTD file:

<!DOCTYPE Newspaper [<! ELEMENT newspaper (article+)><!ELEMENT article (headline,byline,lead,body,notes)><!ELEMENT Headline (#PCDATA)><!ELEMENT byline (#PCDATA)><!ELEMENT Lead (#PCDATA)><!ELEMENT BODY (#PCDATA)><!ELEMENT NOTES (#PCDATA)>  <!attlist article AUTHOR CDATA #REQUIRED><!attlist article EDITOR CDATA #IMPLIED><!attlist article DATE CDATA #IMPLIED><!attlist article EDITION CDATA #IMPLIED>]>

XML in addition to the DTD itself, there is a real schema, called the XML Schema, which itself is XML. In fact, the XML schema is an evolutionary version invented for a DTD that does not solve the problem, you can define the data type, including the collection type, you can specify the order, the number of occurrences of the element, the namespace is supported, the default value is defined, and so on. In addition, even from this point of view, XML is indeed more powerful than JSON:

<?XML version= "1.0"?><Xs:schemaXmlns:xs= "Http://www.w3.org/2001/XMLSchema"> <xs:elementname= "Note">  <Xs:complextype>    <xs:sequence>      <xs:elementname= "to"type= "Xs:string"/>      <xs:elementname= "from"type= "Xs:string"/>      <xs:elementname= "Heading"type= "Xs:string"/>      <xs:elementname= "Body"type= "Xs:string"/>    </xs:sequence>  </Xs:complextype></xs:element> </Xs:schema>

Accordingly, JSON also has something like that, called the JSON Schema, which is itself json. Like this example:

{"    title": "Example Schema",    "type": "Object",    "Properties": {        "FirstName": {            "type": "String"        },        "LastName": {            "type": "String"        },        "age": {            "description": "Age in Years",            " Type ":" "integer", "            Minimum": 0        }    ,    "required": ["FirstName", "LastName"]}

from XPath to Jsonpath

We often need an expression to access a node or attribute in the middle of the XML, and XPath is the expression, such as the following XPath expression, which is the node of the XPath header above the XPath Wikipedia page:

*[@id = "Firstheading"]/span

Why is the path of the JSON data rarely mentioned? The main reason is because once the language is natively supported, we are unconsciously using it, such as using one of the properties of an object in JavaScript as natural. However, in any case, the expression of a path is irreplaceable, in addition to a variety of open source projects, there is a specification called JSON pointer, although not enough to get a vote of approval, but also someone to JSONPath something.

are there other alternatives?

Yes. Yaml, for example, is more informative and eliminates many formatting symbols, such as JSON quotes and XML tag tokens. A description of the YAML website, which compares it to JSON and XML:

JSON ' s foremost design goal is simplicity and universality. In contrast, YAML ' s foremost design goals is human readability and support for serializing arbitrary native data Structur Es. Thus, YAML allows for extremely readable files, but was more complex to generate and parse.

YAML is primarily a data serialization language. XML is designed to support structured documentation. XML therefore had many design constraints placed on it, YAML does not share.

Take a look at the following example, and have to say that Yaml is the best of the three in terms of clarity and brevity:

---Receipt:     Oz-ware Purchase invoicedate:        2007-08-06customer: Given    :   Dorothy    family:  Gale    items:    -Part_no:   A4786      descrip:   water Bucket (Filled) Price      :     1.47      Quantity:  4     -part_no:   E1628      descrip: High   heeled "Ruby" Slippers price       :     100.27      Quantity:  1 bill-to:   &id001    Street: |             123 Tornado Alley            Suite:   East Westville State    :  KS ship-to:  *id001    Specialdelivery:  >    Follow the Yellow Brick    Road to the Emerald city.    Pay no attention      to the man behind the curtain ....

XML and JSON comparisons

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.