I am trying to create a XML to JSON converter app which accepts a custom .xml file and parse the content in it to JSON object using xml2json-ltx library. I have done the parsing/converting part but the result JSON is a bit ugly.
I just want to beautify the parsed JSON and add the proper indentations in the resulting JSON Object. How can I? Please comment/answer with an example please :)
LtxParser.jsx
import React, { useState, useEffect } from "react";
import parser from "xml2json-ltx";
const Ltx = () => {
const [fileState, setFileData] = useState();
const [jsonData, setJsonData] = useState();
useEffect(() => {
if (!!fileState) {
const resultObj = parser.toJson(fileState, {
object: true,
});
setJsonData(resultObj);
}
}, [fileState]);
const onFileDrop = (e) => {
e.preventDefault();
const fileData = e.target.files[0];
const reader = new FileReader();
reader.onload = function (evt) {
setFileData(evt.target.result);
};
reader.readAsText(fileData);
};
return (
<div>
Ltx
<input type="file" onChange={onFileDrop} />
{jsonData && JSON.stringify(jsonData, undefined, 4)}
</div>
);
};
export default Ltx;
Sample.xml
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
</catalog>