Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:

Variable that I will pass to the function will look like this:

[{   "id": 28,   "Title": "Sweden" }, {   "id": 56,   "Title": "USA" }, {   "id": 89,   "Title": "England" }]  function test(myJSON) {   // maybe parse my the JSON variable?   // and then I want to loop through it and access my IDs and my titles } 

Any suggestions how I can solve it?

like image 401
Fredrik Johansson Avatar asked May 09 '10 21:05

Fredrik Johansson


1 Answers

This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

var arrayOfObjects = [{   "id": 28,   "Title": "Sweden" }, {   "id": 56,   "Title": "USA" }, {   "id": 89,   "Title": "England" }];  for (var i = 0; i < arrayOfObjects.length; i++) {   var object = arrayOfObjects[i];   for (var property in object) {     alert('item ' + i + ': ' + property + '=' + object[property]);   }   // If property names are known beforehand, you can also just do e.g.   // alert(object.id + ',' + object.Title); } 

If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]'; var arrayOfObjects = eval(string); // ... 

To learn more about JSON, check MDN web docs: Working with JSON .

like image 165
BalusC Avatar answered Oct 05 '22 23:10

BalusC