JSON and XML are two of the most widely used data formats for exchanging information between applications. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. XML (eXtensible Markup Language) is a markup language that is used to store and transport data. Both JSON and XML have their own advantages and disadvantages, but in many cases, it is necessary to convert data from one format to the other.
In this article, we’ll discuss how to handle and convert JSON to XML and XML to JSON using React, a popular JavaScript library for building user interfaces.
What is XML?
XML, or eXtensible Markup Language, is a markup language used for encoding data in a structured format. It was created as a successor to HTML and is used for storing and exchanging data. XML uses tags to define elements and their attributes, which makes it a flexible and versatile data format.
For example, consider the following XML data:
1 2 3 4 5 6 7 8 9 10 11 12 | <users> <user> <id>1</id> <name>John Doe</name> <email>johndoe@example.com</email> </user> <user> <id>2</id> <name>Jane Doe</name> <email>janedoe@example.com</email> </user> </users> |
In this example, the users
element contains multiple user
elements, each of which contains an id
, name
, and email
element.
What is JSON?
JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. JSON is based on a subset of the JavaScript programming language and is used for exchanging data between systems.
Here’s an example of the same data as above, but in JSON format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "users": [ { "id": 1, "name": "John Doe", }, { "id": 2, "name": "Jane Doe", } ] } |
Simple example to parse XML to JSON in React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import React, { useState, useEffect } from "react"; function App() { const [data, setData] = useState(null); useEffect(() => { const xml = ` <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> `; const parseXml = (xml) => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, "text/xml"); const obj = {}; if (xmlDoc.nodeType === 1) { if (xmlDoc.attributes.length > 0) { obj["@attributes"] = {}; for (let j = 0; j < xmlDoc.attributes.length; j++) { const attribute = xmlDoc.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xmlDoc.nodeType === 3) { obj = xmlDoc.nodeValue; } if ( xmlDoc.hasChildNodes() && xmlDoc.childNodes.length === 1 && xmlDoc.childNodes[0].nodeType === 3 ) { obj = xmlDoc.childNodes[0].nodeValue; } else if (xmlDoc.hasChildNodes()) { for (let i = 0; i < xmlDoc.childNodes.length; i++) { const item = xmlDoc.childNodes.item(i); const nodeName = item.nodeName; if (typeof obj[nodeName] === "undefined") { obj[nodeName] = parseXml(item); } else { if (typeof obj[nodeName].push === "undefined") { const old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(parseXml(item)); } } } return obj; }; setData(parseXml(xml)); }, []); return ( <div> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default App; |
Parse an XML file and convert it to JSON using React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import React, { useState, useEffect } from "react"; function App() { const [data, setData] = useState(null); useEffect(() => { const xmlFile = new XMLHttpRequest(); xmlFile.open("GET", "sample.xml", false); xmlFile.send(); const parseXml = (xml) => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, "text/xml"); const obj = {}; if (xmlDoc.nodeType === 1) { if (xmlDoc.attributes.length > 0) { obj["@attributes"] = {}; for (let j = 0; j < xmlDoc.attributes.length; j++) { const attribute = xmlDoc.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xmlDoc.nodeType === 3) { obj = xmlDoc.nodeValue; } if ( xmlDoc.hasChildNodes() && xmlDoc.childNodes.length === 1 && xmlDoc.childNodes[0].nodeType === 3 ) { obj = xmlDoc.childNodes[0].nodeValue; } else if (xmlDoc.hasChildNodes()) { for (let i = 0; i < xmlDoc.childNodes.length; i++) { const item = xmlDoc.childNodes.item(i); const nodeName = item.nodeName; if (typeof obj[nodeName] === "undefined") { obj[nodeName] = parseXml(item); } else { if (typeof obj[nodeName].push === "undefined") { const old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(parseXml(item)); } } } return obj; }; setData(parseXml(xmlFile.responseText)); }, []); return ( <div> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default App; |
In this example, we use the XMLHttpRequest
API to retrieve the XML file. Then we use the parseXml
function to parse the XML and convert it to JSON, which is then displayed in the UI.
Parse an XML file, convert it to JSON, and save it as a separate file using React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import React, { useState, useEffect } from "react"; function App() { const [data, setData] = useState(null); useEffect(() => { const xmlFile = new XMLHttpRequest(); xmlFile.open("GET", "sample.xml", false); xmlFile.send(); const parseXml = (xml) => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, "text/xml"); const obj = {}; if (xmlDoc.nodeType === 1) { if (xmlDoc.attributes.length > 0) { obj["@attributes"] = {}; for (let j = 0; j < xmlDoc.attributes.length; j++) { const attribute = xmlDoc.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xmlDoc.nodeType === 3) { obj = xmlDoc.nodeValue; } if ( xmlDoc.hasChildNodes() && xmlDoc.childNodes.length === 1 && xmlDoc.childNodes[0].nodeType === 3 ) { obj = xmlDoc.childNodes[0].nodeValue; } else if (xmlDoc.hasChildNodes()) { for (let i = 0; i < xmlDoc.childNodes.length; i++) { const item = xmlDoc.childNodes.item(i); const nodeName = item.nodeName; if (typeof obj[nodeName] === "undefined") { obj[nodeName] = parseXml(item); } else { if (typeof obj[nodeName].push === "undefined") { const old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(parseXml(item)); } } } return obj; }; setData(parseXml(xmlFile.responseText)); const a = document.createElement("a"); const file = new Blob([JSON.stringify(data)], { type: "application/json" }); a.href = URL.createObjectURL(file); a.download = "data.json"; a.click(); }, []); return ( <div> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default App; |
In this example, we use the XMLHttpRequest
API to retrieve the XML file. Then we use the parseXml
function to parse the XML and convert it to JSON. Finally, we use the Blob
API to create a new file with the JSON data, and the URL.createObjectURL
and download
attributes of the a
element to download the file to the client’s machine.
Parse a JSON file and save it as an XML file using the xml2js
library in React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import React, { useState, useEffect } from 'react'; import xml2js from 'xml2js'; import fs from 'fs'; const App = () => { const [xml, setXml] = useState(''); useEffect(() => { fs.readFile('./data.json', 'utf-8', (err, jsonData) => { if (err) { console.error(err); return; } const data = JSON.parse(jsonData); const builder = new xml2js.Builder(); const xmlData = builder.buildObject(data); setXml(xmlData); }); }, []); useEffect(() => { if (!xml) return; fs.writeFile('./data.xml', xml, 'utf-8', (err) => { if (err) { console.error(err); return; } console.log('XML file saved successfully!'); }); }, [xml]); return ( <div> <pre>{xml}</pre> </div> ); }; export default App; |
In this example, we use the useEffect
hook to read the JSON file, parse it, and then convert it to an XML string. The xml2js
library is used to convert the JSON data to an XML string. Finally, the XML string is saved to a file using the fs
module.