We can use the JSON.stringify() method inside the callback function to convert the parsed XML to JSON.įor example, install the package xml2js with the following command. The method also takes a callback function as a parameter. The package contains a method parseString() that parses the XML data. We can convert XML to JSON using the package xml2js in JavaScript. Use the xml2js Package to Convert XML to JSON in JavaScript We use the console.log() method to call the function and display the returned result. Then, we simply return the convertXmlToJson() with the jsonData variable. Recursive functions are called in their braces to iterate the execution. You might wonder why, using console.dir or console.log the output at some level is only Object. You get a string containing the JSON representation of the parsed object that you can feed to JSON-hungry consumers. It is known as recursion (recursive function). So you wanna some JSON Just wrap the result object in a call to JSON.stringify like this JSON.stringify(result). You can see a function called convertXmlToJson() inside the body itself. Inside the body of the loop, we are creating keys and values and storing the result in the already declared variable const jsonData =. In that function, we used the for loop to iterate the execution on the XML string with matchAll(regex). We have declared a function convertXmlToJson() to get the XML string as argument. In the example, we initialized the XML string to a variable to generate JSON data.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |