53

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?

Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
Fredrik Johansson
  • 531
  • 1
  • 5
  • 3

7 Answers7

72

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 .

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 5
    Remember `if (object.hasOwnProperty(...` – Sean Kinsey May 09 '10 at 21:47
  • +1 for eval() update, wasted so much time not realizing I needed to convert the string into an object. – Peadar Doyle May 14 '12 at 16:43
  • 1
    @PeadarDoyle: you're welcome. Please make sure that this string doesn't contain user-controlled data, or you may risk JS code injection. But better would be to pass in a fullworthy JS object already from the beginning on. I.e. remove the quotes surrounding the string -if any. – BalusC May 14 '12 at 16:48
  • +1 bra. I was looking for a way to get Ajax response string to bootstrap multi select. This var arrayOfObjects = eval(string); did the trick – Thakhani Tharage Jul 27 '14 at 10:04
17

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});
Bugs
  • 4,491
  • 9
  • 32
  • 41
Swapnil Godambe
  • 2,054
  • 1
  • 24
  • 29
6

By 'JSON array containing objects' I guess you mean a string containing JSON?

If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.

After that you just iterate over the array as normal.

for (var i = 0; i < myArray.length; i++) {
    alert(myArray[i].Title);
}
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
4

Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:

if you have the JSON string as above then you'd just need to do this

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

then you can access these vars with something like jsonObj[0].id etc

Let me know if that's not what you were getting at and I'll try to help.

M

Martyn
  • 16,432
  • 24
  • 71
  • 104
  • 4
    You shouldn't be using eval() to parse JSON, you know that? Use JSON.parse(). – jpangamarca Jun 15 '15 at 14:55
  • 1
    ^ Because using `eval()` you are more vulnerable since that JS function accepts all JS expressions (https://stackoverflow.com/questions/1843343/json-parse-vs-eval) – Remi Dec 12 '17 at 16:41
2

@Swapnil Godambe It works for me if JSON.stringfy is removed. That is:

$(jQuery.parseJSON(dataArray)).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});
shaosh
  • 657
  • 2
  • 8
  • 30
0

var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); 
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");
Jamhari
  • 13
  • 2
0

// Define a JSON array with objects
var employees = [    {        "name": "John",        "age": 30,        "department": "Sales"    },    {        "name": "Emily",        "age": 28,        "department": "Marketing"    },    {        "name": "Michael",        "age": 35,        "department": "Finance"    }];

// Accessing the objects in the array
console.log(employees[0].name);      // Output: John
console.log(employees[1].age);       // Output: 28
console.log(employees[2].department); // Output: Finance
Json Full Form or What Is Json