简体   繁体   English

将 XML 数据解析为 JSON(或数组)-Javascript/React

[英]Parse XML data to JSON (or array) - Javascript/React

I have an api that fetches XML that looks like this:我有一个 api 获取 XML,看起来像这样:

在此处输入图像描述

As above picture shows, the XML contains several "item" each one contain the following properties: title link description pubdate create guid如上图所示,XML 包含多个“item”,每个“item”包含以下属性: title link description pubdate create guid

How can I convert the above to JSON?我如何将上面的转换为 JSON? Each item as an object with the same properties.每个项目作为具有相同属性的 object。 Or an array for that matter so I can easily handle the data programatically.或者一个数组,这样我就可以轻松地以编程方式处理数据。 I use React.我使用 React。

have a look at xml2json看看xml2json

very simple to use, and can also convert back to XML if needed:使用起来非常简单,如果需要也可以转换回 XML:

var parser = require('xml2json');
 
var xml = "<foo attr=\"value\">bar</foo>";
console.log("input -> %s", xml)
 
// xml to json
var json = parser.toJson(xml);
console.log("to json -> %s", json);
 
// json to xml
var xml = parser.toXml(json);
console.log("back to xml -> %s", xml)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM