XML to JSON
JSON (JavaScript Object Notation) was defined as an alternative to XML. The syntax is fairly simple and based on the JavaScript programming language. In fact, it's possible for a JavaScript program to evaluate a JSON format and use it directly.
But, if you want to convert between XML and JSON, you will very quickly discover that most tools available do not convert between the two perfectly. Some conversion methods result in losing attributes and some produce data structures that are very difficult to convert back into XML and restore the original XML syntax properly.
This page presents a technique for converting between XML and JSON, without losing valuable information. The technique involves converting every XML element into a JSON object. Attributes associated with elements are given a name that is prefixed with '@' and the actual element value is simply represented with the name '$'.
NOTE: since this method does not use array constructs in the resulting JSON, elements will replace any previous occurrences of elements with the same name. As such, this method is only useful if the XML is guaranteed to have unique element names at a given depth.
Consider this sample XML file:
<?xml version="1.0" encoding="UTF-8"?>
<setup version="1" mfg="Packetizer" prod="SampleSystem" rel="1.4">
<sourceAddress type="uri">mailto:alice@example.com</sourceAddress>
<destinationAddress type="tel">+15551212</destinationAddress>
<conferenceID value="F6F48ABE-54AA-4881-862E-DB664DD65CDE"/>
<mediaFlows>
<mediaFlow id="1">
<transport type="udp">
<address type="ipv4">192.168.1.20</address>
<port>46446</port>
<qos type="dscp">ef</qos>
</transport>
</mediaFlow>
</mediaFlows>
</setup>
Performing the XML to JSON conversion, we get this:
{
"setup" : {
"@rel" : "1.4",
"@version" : "1",
"@mfg" : "Packetizer",
"@prod" : "SampleSystem",
"sourceAddress" : {
"@type" : "uri",
"$" : "mailto:alice@example.com"
},
"destinationAddress" : {
"@type" : "tel",
"$" : "+15551212"
},
"conferenceID" : {
"@value" : "F6F48ABE-54AA-4881-862E-DB664DD65CDE"
},
"mediaFlows" : {
"mediaFlow" : {
"@id" : "1",
"transport" : {
"@type" : "udp",
"address" : {
"@type" : "ipv4",
"$" : "192.168.1.20"
},
"port" : {
"$" : "46446"
},
"qos" : {
"@type" : "dscp",
"$" : "ef"
}
}
}
}
}
}
As you can see, all of the important information, including the element data, attributes, etc., are all preserved. One could readily convert this JSON form directly into XML and have the exact same structure as what you started with. (Note the caveat mentioned above!)
You can download sample code written in Perl that can perform this form of XML to JSON conversion.