JavaScript parse JSON

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?


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.


如果您使用jQuery,请执行以下操作:

var myArray = jQuery.parseJSON('[{"title":"Title1"},{"title":"Title2"}]');

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+")");
链接地址: http://www.djcxy.com/p/8482.html

上一篇: 如何将json编码的PHP数组转换为Javascript中的数组?

下一篇: JavaScript解析JSON