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" }
    ]  
  }
}
2
  • I think you are looking for the answer to the following question stackoverflow.com/questions/1773550/… Commented Nov 28, 2012 at 7:50
  • Are you looking to convert it directly into a Javascript object, or do you just want a JSON string? Commented Mar 12, 2013 at 15:35

2 Answers 2

3

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

Its always worked a charm for me.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

+1 for "Be sure to read the accompanying article on the Xml.com O'Reilly site (linked to at the >bottom)."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.