Thursday, July 14, 2011

Example for converting xml document to JSON

We have this example of xml

<menu id="file" value="File" number="50" >
     <popup>
        <menuitem value="New" onclick="CreateNewDoc()" />
        <menuitem value="Open" onclick="OpenDoc()" />
       <menuitem value="Close" onclick="CloseDoc()" />
     </popup>
</menu>

So I will shortly explain the alghorithm to convert xml to 
json code. 
Every json document starts and ends with curly 
brackets {}. Next, menu is a top level tag and contains several 
other subtags so menu is an object. Atributes in the menu tag 
are name/value pairs so in the first step we have this:
 
{
  "menu" : {
  "id" : "file",
  "value" : "File",
  "number" : 50,
  "popup" : ...
}
}

Note that numbers aren't quoted only strings are quoted.
 
Next we will develop the popup and menuitem tags. popup has 
several tags in it so it is an object. Also there are three 
menuitem tags so we need to make an array of them. But also 
every menuitem has several atributes so every menuitem 
is also an object.

We get this:
"popup": {
    "menuitem": [
                {"value": "New", "onclick": "CreateNewDoc()"},
                {"value": "Open", "onclick": "OpenDoc()"},
                {"value": "Close", "onclick": "CloseDoc()"}
    ]
}
We will connect both above examples and now we get this: 
{
"menu": {
    "id": "file",
    "value": "File",
"number" : 50,
    "popup": {
      "menuitem": [
        {"value": "New", "onclick": "CreateNewDoc()"},
        {"value": "Open", "onclick": "OpenDoc()"},
        {"value": "Close", "onclick": "CloseDoc()"}
      ]
    }
  }
}

No comments:

Post a Comment