I used the xml2js
to convert the following xml string to json
export async function parseXml(xmlString: string) {
return await new Promise((resolve, reject) =>
parseString(xmlString, (err: any, jsonData: Book) => {
if (err) {
reject(`Unable to parse to xml due to: ${err}`);
}
console.log(JSON.stringify(jsonData));
resolve([jsonData]);
})
);
}
Below is the xml I am trying to convert
<books>
<book>
<title>harry potter</title>
<author>JK Rowling</author>
<isbn>12fgrwgrgrgrtgrg</isbn>
<quantity>10</quantity>
<price>4.5</price>
</book>
<book>
<title>goosbumps</title>
<author>R.L Stein</author>
<isbn>12fgrwg12334tgrg</isbn>
<quantity>6</quantity>
<price>2.5</price>
</book>
</books>
however once I pass the xml string through the function, I get the following output
{
"books": {
"book": [
{
"title": [
"harry potter"
],
"author": [
"JK Rowling"
],
"isbn": [
"12fgrwgrgrgrtgrg"
],
"quantity": [
"10"
],
"price": [
"4.5"
]
},
{
"title": [
"goosbumps"
],
"author": [
"R.L Stein"
],
"isbn": [
"12fgrwg12334tgrg"
],
"quantity": [
"6"
],
"price": [
"2.5"
]
}
]
}
}
However I wanted something like the following
{
book: {
title: 'harry potter',
author: 'JK Rowling',
isbn: '12fgrwgrgrgrtgrg'
},
stock: {
quantity: 10,
price: 4.5
}
},
{
book: {
title: 'goosbumps',
author: 'R.L Stein',
isbn: '12fgrwg12334tgrg'
},
stock: {
quantity: 6,
price: 2.5
}
}
];
Is there anyway to get it to the format I want without doing some complicated string replacement?