提问人:hulike2286 提问时间:11/8/2022 更新时间:11/8/2022 访问量:51
将 XML 转换为 JSON 后删除其他大括号
remove additional braces after converting xml to json
问:
我使用 将以下 xml 字符串转换为xml2js
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]);
})
);
}
下面是我尝试转换的xml
<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>
但是,一旦我通过函数传递 xml 字符串,我就会得到以下输出
{
"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"
]
}
]
}
}
但是,我想要如下内容
{
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
}
}
];
有没有办法在不进行一些复杂的字符串替换的情况下将其转换为我想要的格式?
答:
1赞
Konrad
11/8/2022
#1
使用选项explicitArray: false
如果为 true,则始终将子节点放在数组中;否则,仅当存在多个数组时,才会创建数组。
评论