Iterate JSON Object String
I am a javascript noob. I have a JSON string created by google gson API after creating the json string which I am passing it to my javascript function. So in a javascript variable
Solution 1:
You can get it into a native JavaScript object with JSON.parse
:
var obj = JSON.parse(yourJSONString);
Then you can iterate the keys with a standard for in loop
for(var k in obj)
if ({}.hasOwnProperty.call(obj, k))
console.log(k, " = ", obj[k]);
Or access particular keys like validationCode
or caseNumber
directly:
var caseNum = obj.caseNumber;
var validationCode = obj.validationCode;
Note that really old browsers don't support JSON.parse
, so if you want to support them, you can either use Papa Crockford's json2, or jQuery, which has a parseJSON utility method.
Solution 2:
You could do a for ... in
to loop through the object properties:
var person={fname:"John",lname:"Doe",age:25};
var x;
for (x in person)
{
document.write(person[x] + " ");
}
Solution 3:
If you are using JQuery framework you can use : jQuery.parseJSON
If not you can use JSON.parse()
or you can use eval
(which is less safe).
Post a Comment for "Iterate JSON Object String"