1

I want to parse an XML file read by $http.get into a JSON object. But every answer I have found is about libraries.

I want to know how can I do it in native Angular without any library -- jQuery not allowed, just AngularJS and vanilla JavaScript.

Any thoughts?

5
  • If you are already getting the xml you could parse through the xml and dynamically create a javascript object. Then use angular.toJson(javascriptObject) to create a JSON Commented Mar 5, 2015 at 20:52
  • Do you think about DOMparser? Commented Mar 5, 2015 at 21:00
  • Forgot to post this link w3schools on xml domparser. @thigrand indeed the domparser. Is this suitable for your situation? Commented Mar 5, 2015 at 21:08
  • Well, actually it's not. In my understanding of course. I want to translate this DOM's tree alike stuff into an object. And use it like a regular object. I don't want to use operations on DOM. It's meaningless in Angular. Commented Mar 5, 2015 at 23:47
  • I just googled and found this it is native see this blogpost Commented Mar 6, 2015 at 6:19

1 Answer 1

1

I would personally recommend having a look at xml2json. It can convert your XML to JSON by using only basic JavaScript, so without the need of jQuery or external libraries. It is also very lightweight (around 100 lines of code) -- but still a bit much to inline rather than link here. You can simply add the functions to your code and use it as you wish.

It takes the XML attributes into considerations. Here is how to use it:

var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
var json = xml2json(xml); 

console.log(json); 
// prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’

You can also try out the online demo here : https://jsfiddle.net/enkidootech/ogsousqd/18/

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.