我正在尝试从 URL 解析 XML 响应并将其转换为 JSON,解析的响应有很多不需要的数据,但是我只需要属性“TEXT”的值

尝试通过调用output = JSON.stringify(result);来获取 key 并返回 return output['TEXT'];但它给出了一个未定义的错误。

var parseString = require('xml2js').parseString; 
 
function parse() 
{ 
 
http.get('http://data.alexa.com/data?cli=10&url=https://google.com',  
(resp) => { 
let data = ''; 
// A chunk of data has been recieved. 
resp.on('data', (chunk) => { 
    data += chunk; 
}); 
// The whole response has been received. Print out the result. 
resp.on('end', () => { 
 
//console.log(JSON.parse(data).explanation); 
    parseString(data, function (err, result) { 
        console.log(JSON.stringify(result)); 
            output = JSON.stringify(result); 
 
             }); 
}); 
}).on("error", (err) => { 
console.log("Error: " + err.message); 
}); 
 
return output['TEXT']; 
} 

这是解析函数返回的完整 JSON,我认为它无效。我试图获取“POPULARITY”内的“TEXT”值

{"ALEXA":{"$":  
   {"VER":"0.9","URL":"google.com/","HOME":"0","AID":"=","IDN":                                         
   "buymeacoffee.com/"},"SD":[{"POPULARITY":[{"$":  
   {"URL":"google.com/","TEXT"                                         
   :"20242","SOURCE":"panel"}}],"REACH":[{"$":{"RANK":"25887"}}],"RANK":  
   [{"$":  
   {"DEL                                        TA":"-21167"}}],"COUNTRY":  
   [{"$":{"CODE":"US","NAME":"United States","RANK":"2093                                         
   5"}}]}]}} 

请您参考如下方法:

关于你在这里做错了什么:

  • 您不需要对 parseString 的结果进行字符串化。它已经是一个对象,您可以按原样使用它。

  • 如果你想访问text,可以通过result['ALEXA']['SD']['POPULARITY']['$'][来实现'文本']

或者:

您可以尝试使用camaro 。它是专门为此目的而设计的:将 xml 转换为 json,并仅获取您感兴趣的属性。

const { transform } = require('camaro') 
 
const xml = ` 
 
<?xml version="1.0" encoding="UTF-8"?> 
 
<!-- Need more Alexa data?  Find our APIs here: https://aws.amazon.com/alexa/ --> 
<ALEXA VER="0.9" URL="google.com/" HOME="0" AID="=" IDN="google.com/"> 
<SD><POPULARITY URL="google.com/" TEXT="1" SOURCE="panel"/><REACH RANK="1"/><RANK DELTA="+0"/><COUNTRY CODE="US" NAME="United States" RANK="1"/></SD></ALEXA> 
` 
 
;(async function () { 
    const template = { 
        text: 'ALEXA/SD/POPULARITY/@TEXT' 
    } 
 
    const result = await transform(xml, template) 
 
    console.log(JSON.stringify(result, null, 4)); 
 
})() 

输出:

{ 
    "text": "1" 
} 

您想要的text属性可以通过使用result.text来访问


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!