-4

If my json is this:

[
     ["cat1"],
     ["cat2"],
     ["cat3"],
     ["cat4"],
     ["cat5"]
]

How to parse this in javascript. I am looking for some for loop kind of solution which can iterate over the json and can give me "cat1 ", "cat2" etc.

P.S.: My json list is dynamic which i am getting from some source. So, i dont know how my json elements are there and what are the fields.

ujjawl saini
  • 133
  • 3
  • 15

2 Answers2

0

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:

var json = '{"result":true,"count":1}', obj = JSON.parse(json);

alert(obj.count); For the browsers that don't you can implement it using json2.js.

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}', obj = JSON && JSON.parse(json) || $.parseJSON(json);

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

0

try this.

var list= [
     ["cat1"],
     ["cat2"],
     ["cat3"],
     ["cat4"],
     ["cat5"]
];
    list.forEach(function(item){
      console.log(item[0]);
    });
kamprasad
  • 608
  • 4
  • 12