javascript - Iterate over String of JSON Format -
i passing mongodb query result in string format jsp page using ajax. retrieving data don't know how iterate on data.
note : json structure of dynamic schema given below
query result in string format
[ { "_id":"...", "user":"john doe", "hobbies":["1","2","3"], "address":{ "city":"...", "state":"...", "country":"..." }, "cell":97265xxxxx }, { "_id":"...", "user":"john doe", "hobbies":["1","2","3"], "cell":97265xxxxx } ... ]
first converting json string javascript object using jquery parsejson() & trying loop on data showing me undefined.
here code
<button>click me</button><br/> <p id="p0"></p> <p id="p1"></p> <p id="p2"></p> <p id="p3"></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").on("click",function(){ $.ajax({ url:'quizdemoservlet', type:'post', success:function(data) { //json string fetched $("#p0").html(data); var jso = $.parsejson(data); alert("jso " +jso.length); for(var iterate=0; iterate<jso.length; iterate++){ $("#p1").append(iterate["user"]+"<br>"); $("#p2").append(iterate["hobbies"]+"<br>"); $("#p3").append(iterate["cell"]+"<br>"); } }, error:function(msg){ alert("error"); console.log(msg); } }); }); }); </script>
firstly, assume json correct. if so, make sure in form:
[ { "_id":"...", "user":"john doe", "hobbies":["1","2","3"], "address":{ "city":"...", "state":"...", "country":"..." }, "cell":"97265xxxxx" }, { "_id":"...", "user":"john doe", "hobbies":["1","2","3"], "cell":"97265xxxxx" }, ...... { ..... } ]
make sure validate using validators such http://jsonlint.com/
your json array of objects
. so, iterating on array in javascript.
lets assume variable data
holds json.
var data = json.parse(your_json_string); // json `string`. need `parse` convert javascript object, can iterate on it.
in case, can this:
for(var obj=0;obj<data.length;obj++){ // each object here. //obj['_id'] // obj['user'] // since schema dynamic, make sure key exists before access if(data[obj].hobbies!= undefined){ //iterate on hobbies. } if(data[obj].address!=undefined){ var city = data[obj].address.city; var state = data[obj].address.state; var country= data[obj].address.country; } ....and on }