如何在JSON对象中读取数组,这是在另一个数组中

时间:2014-11-19 09:38:27

标签: javascript json parsing

我是JSON的新手,我正在解析一个JSON对象,我被打到了一个点,我必须读取一个Object内的数组元素,这又是另一个数组。  这是MY JSON

   {
"DefinitionSource": "test",
"RelatedTopics": [
    {
        "Result": "",
        "Icon": {
            "URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
        },
        "FirstURL": "xyz",
        "Text": "sample."
    },
    {
        "Result": "",
        "Icon": {
            "URL": "xyz"
        },
        "FirstURL": "xyz",
        "Text": "sample."
    },
    {
        "Topics": [
            {
                "Result": "",
                "Icon": {
                    "URL": "https://duckduckgo.com/i/10d02dbf.jpg"
                },
                "FirstURL": "https://duckduckgo.com/Snake_Indians",
                "Text": "sample"
            },
            {
                "Result": "sample",
                "Icon": {
                    "URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
                },
                "FirstURL": "www.google.com",
                "Text": "xyz."
            }
        ]
    }
]
}

这里我需要从RelatedTopics数组和Topics数组中读取URL,FIRSTURL和Text。 谁能帮我。提前致谢。

2 个答案:

答案 0 :(得分:1)

像这样的东西

function (json) {
    json.RelatedTopics.forEach(function (element) {
        var url = element.Icon ? element.Icon.URL : 'no defined';
        var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
        var text = element.Text ? element.Text : 'no defined';
        alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);

        if (element.Topics)
        {
            element.Topics.forEach(function (topicElement) { 
                alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
            }); 
        }
    });
};

Look fiddle example

答案 1 :(得分:0)

循环通过json数组,

for(var i=0; i< RelatedTopics.length;i++){

     if($.isArray(RelatedTopics[i])){
       for(var j=0; j< RelatedTopics[i].Topics.length;j++){
        var topics=RelatedTopics[i].Topics[j];
        var text = topics.Text;
        var firsturl = topics.Firsturl;
        var url = topics.Icon.url;
       }

     }
}

如果你想推它一个数组变量