JavaScript解析JSON

JavaScript parse JSON

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How to parse JSON in JavaScript

我有这个json字符串:

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

如何解析它,以便获得每个标题?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var string = '[{"title":"Title1
<hr>
<p>
If that'
s directly in your JS then it works out of the box:
</p>

[cc lang="javascript"]var obj = [{"title":"Title1
<p><center>[wp_ad_camp_1]</center></p><hr>
<p>
If you're using jQuery just do:
</p>

[cc lang="
javascript"]var myArray = jQuery.parseJSON('[{"title":"Title1
<hr>
<p>
Using a for loop, perhaps? :o
</p>

[cc lang="javascript"]for(var i = 0; i < jsonVar.length; i++) {
   alert(jsonVar[i].title);
}

下面是一个使用jquery的示例:

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

?您可以在这里看到一个演示:http://jsfiddle.net/pbb4j/


使用JSON.parse(json2.js将为较旧的浏览器提供该版本)。


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