解析 JSON 以获取 javascript 中对象内数组中的值

Parsing JSON to get values in array inside a object in javascript

本文关键字:数组 对象 解析 获取 javascript JSON      更新时间:2023-09-26

我是JSON和Javascript的新手,所以,帮我在JSON中的对象中找到数组值。在这里,我有一个这样的 JSON 对象

{
"DefinitionSource": "",
"ImageWidth": 0,
"RelatedTopics": [
{
    "Result": "<a href='"https://duckduckgo.com/Ashok_Shinde'">Ashok Shinde</a>An Indian film and stage actor, who works in Marathi cinema, known for films like Rangat Sangat.",
    "Icon": {
        "URL": "",
        "Height": "",
        "Width": ""
    },
    "FirstURL": "https://duckduckgo.com/Ashok_Shinde",
    "Text": "Ashok ShindeAn Indian film and stage actor, who works in Marathi cinema, known for films like Rangat Sangat."
},
{
    "Result": "<a href='"https://duckduckgo.com/R._Ashok'">R. Ashok</a>R. Ashok is a leader of the Bharatiya Janata Party in Karnataka, India.",
    "Icon": {
        "URL": "",
        "Height": "",
        "Width": ""
    },
    "FirstURL": "https://duckduckgo.com/R._Ashok",
    "Text": "R. AshokR. Ashok is a leader of the Bharatiya Janata Party in Karnataka, India."
},
{
    "Result": "<a href='"https://duckduckgo.com/Ashok_(film)'">Ashok (film)</a>",
    "Icon": {
        "URL": "https://duckduckgo.com/i/37704bcf.jpg",
        "Height": "",
        "Width": ""
    },
    "FirstURL": "https://duckduckgo.com/Ashok_(film)",
    "Text": "Ashok (film)A 2006 Telugu film directed by Surender Reddy."
}
],
"Entity": "",
"Results": [],
"Answer": ""
}

在这个JSON中,我想从ICON对象中获取"URL",并从"相关主题"中的每个对象中获取"TEXT"。但我找不到方法。请帮助摆脱这个问题。提前致谢

您必须循环对象数组并使用索引来检查每个对象的属性:

for (var i = 0; i < data.RelatedTopics.length; i++) {
    console.log(data.RelatedTopics[i].Text); //text;
    console.log(data.RelatedTopics[i].Icon.URL) //url;
}

你也可以试试

results.map(function(e){ return e.Icon.URL; });