4

I have an XML file with the following content:

<directory>
  <app>
    <title>Carrot</title>
    <url>www.carrot.com</url>
  </app>
  <app>
    <title>Cucumber</title>
    <url>www.cucumber.com</url>
  </app>
</directory>

Assuming I had been able to read it and store the content as a string:

s = '<directory><app><title>Carrot</title><url>www.google.com</url></app><app><title>Cucumber</title><url>www.cucumber.com</url></app></directory>';

How do I convert it to a JavaScript object like the following?

{
  "directory": {
    "app": [
      { "title": "Carrot", "url": "www.carrot.com" },
      { "title": "Cucumber", "url": "www.cucumber.com" }
    ]  
  }
}
moey
  • 10,587
  • 25
  • 68
  • 112

2 Answers2

3

I use this plugin ... http://www.thomasfrank.se/xml_to_json.html

Its always worked a charm for me.

Blowsie
  • 40,239
  • 15
  • 88
  • 108
2

I think you are looking for the answer to the following question Convert XML to JSON (and back) using Javascript

XML <-> JSON conversion in Javascript

quoted answer

I think this is the best one: Converting between XML and JSON

Be sure to read the accompanying article on the Xml.com O'Reilly site (linked to at the >bottom). The writer goes into details of the problems with these conversions, which I think >you will find enlightening. The fact that O'Reilly is hosting the article should indicate >that Stefan's solution has merit.

Community
  • 1
  • 1
Christian Westman
  • 2,985
  • 1
  • 26
  • 28