如何迭代从 XML 转换而来的 JSON 数组?

How do I iterate over JSON array that is converted from XML?

我有一个函数调用另一个函数从 axios 获取数据。我无法遍历 json 对象的数组。它显示为未定义,我不确定为什么?

最终函数:

async function final(){
    let final = []
    let data1 = await getPeople();
    let data2 = await getXml();
    for(i=0;i<data1.length;i++){
        final.push(data1[i]);
    }
    console.log(data2.persons.person)
    for(j=0;j<data2.persons.person.length;j++){
        final.push(data2[j])
    }
    final.sort();
    return final;
}

获取xml函数:

async function getXml(){
let ans;
const {data} = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml');
xml2js.parseString(data, (err, result) => {
    if(err) {
        throw err;
    }

    const json = JSON.stringify(result, null, 4);

    ans = json
    
});
return ans;

}

我正在从 xml 函数中正确获取数据,但我该如何遍历 person?

您的代码有几个问题。首先,您不想将 xml2js 解析的结果字符串化。您想将其保留为 JavaScript 对象。

其次,您没有迭代结果中的正确节点。您正确记录了它,但随后遍历了父节点。这是对您的代码的最小修复:

import axios from 'axios';
import xml2js from 'xml2js';

async function getXml() {
  let ans;
  const { data } = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml');
  xml2js.parseString(data, (err, result) => {
    if (err) {
      throw err;
    }

    // const json = JSON.stringify(result, null, 4);

    ans = result;
  });
  return ans;
}

async function final() {
  const final = [];
  // const data1 = await getPeople();
  const data2 = await getXml();
  // for (let i = 0; i < data1.length; i++) {
  //   final.push(data1[i]);
  // }
  console.log(data2.persons.person);
  for (let j = 0; j < data2.persons.person.length; j += 1) {
    final.push(data2.persons.person[j]);
  }
  final.sort();
  return final;
}

console.log(await final());

还有其他可以清理的东西,但这会让你继续。

你可以像这样用camaro做这个转换。会更简单

const { transform } = require('camaro')

async function main() {
    const xml = `
<persons>
   <person>
       <id>3</id>
       <firstName>Jen</firstName>
       <lastName>Doe</lastName>
   </person>
   <person>
       <id>6</id>
       <firstName>Stephanie</firstName>
       <lastName>Joe</lastName>
   </person>
   <person>
       <id>1</id>
       <firstName>Victoria</firstName>
       <lastName>Doe</lastName>
   </person>
</persons>
`

    const template = {
        persons: ['persons/person', {
            id: 'id',
            firstName: 'firstName',
            lastName: 'lastName'
        }]
    }
    const { persons } = await transform(xml, template)
    console.log(persons);
}

main()

输出

[
  { id: '3', firstName: 'Jen', lastName: 'Doe' },
  { id: '6', firstName: 'Stephanie', lastName: 'Joe' },
  { id: '1', firstName: 'Victoria', lastName: 'Doe' }
]