Converting between XML and JSON

Source: Internet
Author: User
Document directory
  • A pragmatic approach
  • Preserving order
  • Semi-structured XML
  • Examples
URL: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html? CMP = OTC-TY3388567169 & ATT = converting + between + XML + and + JSON

Converting between XML and JSON

By Stefan goessner
May 31,200 6

More and more web service providers seem to be interested in offering JSON APIs beneath their XML APIs. One considerable advantage of using a json api is its ability to provide cross-domain requests while bypassing the restrictiveSame Domain PolicyOf the XMLHTTPRequest object. On the client-side, JSONComes with a native language-compliant data structure, with which it performs much better than corresponding Dom callrequired for XML processing. finally, transforming JSON structures to presentational data can be easily achieved with tools such as jsont.

So if you're working in this space, you probably need to convert an existing XML document to a JSON structure while preserving the following:

  • Structure
  • Order
  • Information

In an ideal world, the resulting JSON structure can be converted back to its original XML document easily. thus it seems worthwhile to discuss some common patterns as the foundation of a potentially bidirectional conversion process between XML and JSON. A similar discussion can be found at badgerfish and Yahoo -- without the reversibility aspect though.

A pragmatic approach

A single structured XML element might come in seven flavors:

  1. An empty Element
  2. An element with pure text content
  3. An empty element with attributes
  4. An element with pure text content and attributes
  5. An element containing elements with different names
  6. An element containing elements with identical names
  7. An element containing elements and contiguous text

The following table shows the corresponding conversion patterns between XML and JSON.

Pattern XML JSON Access
1 <e/> "e": null o.e
2 <e>text</e> "e": "text" o.e
3 <e name="value" /> "e":{"@name": "value"} o.e["@name"]
4 <e name="value">text</e> "e": { "@name": "value", "#text": "text" } o.e["@name"] o.e["#text"]
5 <e> <a>text</a> <b>text</b> </e> "e": { "a": "text", "b": "text" } o.e.a o.e.b
6 <e> <a>text</a> <a>text</a> </e> "e": { "a": ["text", "text"] } o.e.a[0] o.e.a[1]
7 <e> text <a>text</a> </e> "e": { "#text": "text", "a": "text" } o.e["#text"] o.e.a

Please note that all patterns are considered to describe structured elements, despite the fact that the element of pattern 7 is commonly understood as a semistructured element. A pragmatic approach to convert an XML document to a JSON structure and vice versa can be based on the seven patterns above. it always assumes a normalized XML document for input and doesn't take into consideration the following:

  • XML Declaration
  • Processing instructions
  • Explicit handling of namespace declarations
  • XML comments

Preserving order

JSON is built on two internal structures:

  • A collection of name/value pairs with unique names (Associative array)
  • An ordered list of values (Array)

An attempt to map a structured XML element...

<e>
<a>some</a>
<b>textual</b>
<a>content</a>
</e>

... To the following JSON object:

"e": {
"a": "some",
"b": "textual",
"a": "content"
}

YieldsInvalid result, Since the name"a"IsNot uniqueIn the associative array. So we need to collect all elements of identical names in an array. Using the patterns 5 and 6 abve yields the following result:

"e": {
"a": [ "some", "content" ],
"b": "textual"
}

Now we have a structure that doesn't preserve element order. This may or may not be acceptable, depending on whether the above XML Element order matters.

So, our general rules of thumb are:

A structured XML element can be converted toReversibleJSON structure, if

  • All subelement names occur exactly once, or...
  • Subelements with identical names are in sequence.

And

A structured XML element can be converted toIrreversibleButSemantically equivalentJSON structure, if

  • Multiple homonymous subelements occur nonsequentially, and...
  • Element order doesn' t matter.

If none of these two conditions apply, there is no pragmatic way to convert XML to JSON using the patterns above. here, SVG and SMIL Documents, which implicitly rely on element order, come to mind.

Semi-structured XML

XML documents can containSemi-structured elements, Which are elements with mixed content of text and child elements, usually seen in documentation markup. If the textual content is contiguous, as in:

<e>
some textual
<a>content</a>
</e>

We can apply pattern 7 and yield the following for this special case:

"e": {
"#text": "some textual",
"a": "content",
}

But how do we convert textual content mixed up with elements? For example:

<e>
some
<a>textual</a>
content
</e>

It obviously doesn' t make sense in most cases to collect all text nodes in an array,

"e": {
"#text": ["some", "content"],
"a": "textual"
}

That doesn't preserve order or semantics.

So the best pragmatic solution is to treat mixed semi-structured content in JSON the same way as XML treats CDATA sections --Unknown Markup.

"e": "some <a>textual</a> content"

Another rule is that XML elements

  • Mixed content of text and element nodes and
  • CDATA sections

Are converted to a reversible JSON string containing the complete XML markup according to Pattern 2 or 4.

Examples

Now let's look at two examples using the insight we 've ve gained thus far. microformats are well suited because they are an open standard and short enough for a brief discussion.

XOXO, as a simple XHTML-based outline format, is one of several microformats. The slightly modified sample from the draft Specification reads:

<ol class="xoxo">
<li>Subject 1
<ol>
<li>subpoint a</li>
<li>subpoint b</li>
</ol>
</li>
<li><span>Subject 2</span>
<ol compact="compact">
<li>subpoint c</li>
<li>subpoint d</li>
</ol>
</li>
</ol>

Now we apply the patterns abve to convert this XML document fragment to a JSON structure.

  1. The outer list with two list items is converted using pattern 6.
  2. The first list item contains a single textual content"Subject 1"And an inner list element. So, it can be treated according to pattern 7.
  3. The first inner list is converted with pattern 6 again.
  4. Pattern 5 is applied to the second item of the outer list.
  5. The second inner list is converted using a combination of patterns 3 and 6.

Here is the resulting JSON structure, which is reversible without losing any information.

"ol": {
"li": [
{
"#text": "Subject 1",
"ol": {
"li": ["subpoint a", "subpoint b"]
}
},
{
"span": "Subject 2",
"ol": {
"@compact": "compact",
"li": ["subpoint c", "subpoint d"]
}
}
]
}

Hcalendar is another microformat Based on the icalendar standard. we'll just ignore the fact that the icalendar format cocould be more easily converted to JSON, and will look at an hcalendar event example, which is also slightly modified so that it is a structured, rather than mixed, semi-structured document fragment.

<span class="vevent">
<a class="url" href="http://www.web2con.com/">
<span class="summary">Web 2.0 Conference</span>
<abbr class="dtstart" title="2005-10-05">October 5</abbr>
<abbr class="dtend" title="2005-10-08">7</abbr>
<span class="location">Argent Hotel, San Francisco, CA</span>
</a>
</span>

Here, patterns 2, 3, 4, 5 and 6 are used to generate the following JSON structure:

"span": {
"a": {
"@class": "url",
"@href": "http://www.web2con.com/",
"span": [
{ "@class": "summery", "#text": "Web 2.0 Conference" },
{ "@class": "location", "#text": "Argent Hotel, San Francisco, CA" }
},
"abbr": [
{ "@class": "dtstart", "title": "2005-10-05", "#text": "October 5" },
{ "@class": "dtend", "title": "2005-10-08", "#text": "7" }
}
}
}

This example demonstrates a conversion that does not preserve the original element order. Even if this may not change semantics here, we can do the following:

  1. State that a conversion isn' t sufficiently possible.
  2. Tolerate the result if order doesn't matter.
  3. Try to make our XML document more JSON-friendly.

In our cases the last point may not acceptable, at least when the XML document is based on existing standards. but in other cases, it may be worth the effort to consider some subtle XML changes, which can make XML and JSON play nicely together. changing<abbr>Elements<span>Elements inHcalendarExample wocould be an improvement.

XML is a document-centric format, while JSON is a format for structured data. this fundamental difference may be irrelevant, as XML is also capable of describing structured data. if XML is used to describe highly structured documents, these may play very well together with JSON.

Problems may arise, if XML documents do the following:

  • Implicitly rely on element order
  • Contain a lot of semi-structured data

As proof of this concept, I have implemented two JavaScript Functions,

  • xml2json
  • json2xml

Based on the six patterns above, which can be used for the following:

  • Client-side Conversion

    • A parsed XML document via Dom to a JSON Structure
    • A json structure to a (textual) XML document
  • Implementing converters in other server side languages ages

Future XML document design may be influenced by these or similar patterns in order to get the best of the both the XML and JSON worlds.

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.