I have a function that calls another function to get data from axios. I am not able to iterate over the array of the json object. It shows as undefined, I am not sure why?
The final function:
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;
}
Get xml function:
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;
}
I am getting the data correctly from the xml function but how do I iterate over person?
CodePudding user response:
There are several problems with your code. First, you do not want to stringify the result of the xml2js parsing. You want to keep it a JavaScript object.
Second, you don't iterate over the correct node in your results. You log it correctly, but then you iterate over a parent node. This is a minimal fix to your code:
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());
There are other things that could be cleaned up, but this will get you going.