我想知道我可以将 XML 解析为 JSON 而不需要来自第一个 xml 转换的两个第一个元素,而是像第二个转换那样的结果。xml2js 给了我第一次转换。
<?xml version="1.0"?>
<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>
当我用 xml2json 转换它时,我得到这个输出:
`{
"catalog": {
"book": [
{
"-id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications
with XML."
},
{
"-id": "bk102",
"author": "Ralls, Kim",
"title": "Midnight Rain",
"genre": "Fantasy",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world."
}
]
}
}`
但我想要这个输出:
`[
{
"@id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
},
{
"@id": "bk102",
"author": "Ralls, Kim",
"title": "Midnight Rain",
"genre": "Fantasy",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."
}
]`
原因是我需要将其插入到我的 mongodb 中,但第一次转换仅将所有 json 作为一个条目放入我的数据库中。此外,我有一个 csv 插入(我也在 JSON 中转换),它与第二种格式匹配并正确插入到数据库中。有没有办法获得第二种格式而不是第一种格式?
您始终可以将 XML 转换为 JS 对象并对其进行操作,从而删除不必要的数据。
例子
const obj = xml2json.toJson(xml, { object: true });
const books = obj.catalog.book;
// here you have an array of JS objects stored in your variable books
// and you can perform operations
// just an example for mongo insertion
const collection = db.collection('books');
collection.insertMany(books).then(function () {
console.log('books inserted')
})
可以在此处找到解析器的全套选项
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句