Iterating over JSON object in jquery
32,820
Solution 1
your json objects jsonObject
are stored in an array. Do :
$.each(jsonArray, function(index,jsonObject){
$.each(jsonObject, function(key,val){
console.log("key : "+key+" ; value : "+val);
});
});
it will gives you
key : DisplayName ; value : Answer Number 1
key : Value ; value : Answer 1
key : Option ; value : true
Anyway, Anthony is right. Your structure will be difficult to manipulate
Solution 2
Your JSON isn't valid. What about this :
var json = '[
{"DisplayName":"Answer Number 1","Value":"Answer1","Option":"True"},
{"DisplayName":"Answer Number 1","Value":"Answer1","Option":"False"},
{"DisplayName":"Answer Number 2","Value":"Answer2","Option":"True"},
{"DisplayName":"Answer Number 2","Value":"Answer2","Option":"False"}
]';
var jsonObject = $.parseJSON(json); //Only if not already an object
$.each(jsonObject, function (i, obj) {
alert(obj.DisplayName);
});
Solution 3
Use jQuery.each()
$.each( yourArrayOfObjects, function( index, object ){
// do your magic here
});
Comments
-
Gautam almost 4 years
I have a json object as
[ {"DisplayName":"Answer Number 1","Value":"Answer1","Option":"True"}, {"DisplayName":"Answer Number 1","Value":"Answer1","Option":"False"}, {"DisplayName":"Answer Number 2","Value":"Answer2","Option":"True"}, {"DisplayName":"Answer Number 2","Value":"Answer2","Option":"False"} ]
What I need is to create 2 drop downs from this object as
Answer Number 1 -> True/False
Answer Number 2 -> True/False
dropdown part I'll do my self.. I m just confused on how to iterate over this object. Can any1 please lead me to some example?
-
Vipertecpro almost 4 yearsThx alot this one helped