Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I get a JSON object from an AJAX call that I need to get all the "name" values from.

I have tried to iterate it in many different ways without success. I have managed to iterate JSON objects before but now the values are inside pkg which is inside data: and that is where i get trouble. code below does not work and I do not know how to get into pkg.

for (var key in jsonData) {
    if (jsonData.hasOwnProperty(key)) {

    }
    jQuery('#result').html(jsonData[key].join("<br/>"));
}

No success with (jsonData.pkg) or (jsonData.data.pkg) either.

Underneath is the value inside jsonData object.

{
    "data": {
        "pkg": [{
            "name": "ThisIsName1",
            "FRONTPAGE": "n",
            "IP": "n",
            "MAXSQL": "1",
            "MAXPOP": "unlimited"
        }, {
            "name": "ThisIsName2",
            "FRONTPAGE": "n",
            "IP": "n",
            "MAXSQL": "0",
            "MAXPOP": "unlimited"
        }, {
            "name": "ThisIsName3",
            "FRONTPAGE": "n",
            "IP": "n",
            "MAXSQL": "0",
            "MAXPOP": "unlimited"
        }]
    },
    "metadata": {
        "version": 1,
        "reason": "OK",
        "result": 1,
        "command": "listpkgs"
    }
}

I have searched the forum for answers but I have not found someone that has the values nested inside the object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this code. Ensure you have parsed the json string. And use array map function to get all names.

var jsonString = '{"data":{"pkg":[{"name":"ThisIsName1","FRONTPAGE":"n","IP":"n","MAXSQL":"1","MAXPOP":"unlimited"},{"name":"ThisIsName2","FRONTPAGE":"n","IP":"n","MAXSQL":"0","MAXPOP":"unlimited"},{"name":"ThisIsName3","FRONTPAGE":"n","IP":"n","MAXSQL":"0","MAXPOP":"unlimited"}]},"metadata":{"version":1,"reason":"OK","result":1,"command":"listpkgs"}}';

var jsonData = JSON.parse(jsonString);
var names = jsonData.data.pkg.map(function(pkg){ return pkg.name }).join("<br/>");
jQuery('#result').html(names);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...