1

Possible Duplicate:
How to parse JSON in JavaScript

I have this JSON string:

[{"title": "Title1"}, {"title": "Title2"}]

How can I parse it, so that I can get each title?

Community
  • 1
  • 1
somehut
  • 139
  • 2
  • 4
  • 10

7 Answers7

13
var string = '[{"title":"Title1"},{"title":"Title2"}]';

var array = JSON.parse(string);
array.forEach(function(object) {
  console.log(object.title);
});

Note that JSON.parse isn't available in all browsers; use JSON 3 where necessary.

The same goes for ES5 Array#forEach, of course. This is just an example.

If you're using jQuery, you could use $.each to iterate over the array instead. jQuery has a jQuery.parseJSON method, too.

Sharon
  • 919
  • 7
  • 7
3

If you're using jQuery just do:

var myArray = jQuery.parseJSON('[{"title":"Title1"},{"title":"Title2"}]');
davidethell
  • 11,708
  • 6
  • 43
  • 63
3

If that's directly in your JS then it works out of the box:

var obj = [{"title":"Title1"},{"title":"Title2"}];
alert(obj[0].title); // "Title1";

If it's received via AJAX:

// obj contains the data
if( typeof JSON != "undefined") obj = JSON.parse(obj);
else obj = eval("("+obj+")");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Using a for loop, perhaps? :o

for(var i = 0; i < jsonVar.length; i++) {
   alert(jsonVar[i].title);
}
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
0

Use JSON.parse().

Not all browsers have support for that method, so you can use Douglas Crockford's polyfill. Here: https://github.com/douglascrockford/JSON-js

EDIT: Here's the browser support stats for it: http://www.caniuse.com/#search=JSON

Francisc
  • 77,430
  • 63
  • 180
  • 276
0

With JSON.parse (json2.js will provide a version of that for older browsers).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Here's an example, using jQuery:

var jsonObj = $.parseJSON('[{"title": "Title1"}, {"title": "Title2"}]');
var title1 = jsonObj[0].title; //Title1
var title2 = jsonObj[1].title; //Title1

​You can see a demo here: http://jsfiddle.net/pBb4j/

Telmo Marques
  • 5,066
  • 1
  • 24
  • 34