0

Im trying to build an application that fetches data from an web API that returns XML. I want this data in JSON instead, but the API does not support that.

How do i fetch the data and convert it to JSON?

I tried to use xml2js and it seems to work, but i dont understand how to save it as an object so i can use it in my app.

async componentDidMount(){
    const url = "this is where the APIurl are";

    fetch(url)
        .then(res => res.text())
        .then(body => parseString(body, function (err, result) {
            console.log(result);
        })

            );
}

result seems to return the data as json, but i cant figure out how to use the data as an object later.

Stains
  • 97
  • 1
  • 12
  • Possible duplicate of [Convert XML to JSON (and back) using Javascript](https://stackoverflow.com/questions/1773550/convert-xml-to-json-and-back-using-javascript) – luissmg Feb 25 '19 at 14:18

1 Answers1

0

Your best option is to use an external lib to do that. A quick search in google and I found this one https://www.npmjs.com/package/xml-js.

You should also check this question: Convert XML to JSON (and back) using Javascript

To store it on your app you should grab what you need from the parsed XML and put it on the state.

luissmg
  • 545
  • 4
  • 9