Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - How to iterate JSON object properly?

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...