4

I have json array like

var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]'

How to parse the the data and iterate through it using prototype.js?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jetson John
  • 3,759
  • 8
  • 39
  • 53
  • [Searching for `prototypejs parse json`](https://.google.com/search?q=prototypejs+parse+json) lead me to [the official Prototype.js documentation](http://prototypejs.org/doc/latest/language/String/prototype/evalJSON/). And how to iterate over arrays should be explained in every good JavaScript tutorial, for example: http://eloquentjavascript.net/chapter4.html. – Felix Kling Mar 26 '13 at 12:37
  • possible duplicate of [I have a nested data structure / JSON, how can I access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) – Felix Kling Mar 26 '13 at 12:39

1 Answers1

1

There is a function called evalJSON()

var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]';
data = data.evalJSON();
//for more security:
data = data.evalJSON(true); //sanitizes data before processing it

Then just use for to iterate through the array:

for (var i=0;i<data.length;i++)
{ 
    //do whatever you like with data[i];
}

Or use the prototypeJS .each() function:

data.each(function(el){
    //do whatever you like with el
});
user1950929
  • 874
  • 1
  • 9
  • 17
  • actually you can use the `each()` method to iterate through the data http://api.prototypejs.org/language/Enumerable/prototype/each/ – Geek Num 88 Mar 26 '13 at 15:41