Reputation: 123
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?
Upvotes: 1
Views: 1080
Reputation: 36
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/
Upvotes: 1