如何在Javascript中解析Json数组?

时间:2011-11-21 12:29:42

标签: javascript json parsing

以下Json Array易于解析,

{
    "movieCategories": [
       "a" : "Animation",
         "b" :"Romance",
        "c" :"Science Fiction"
       "d" : "Western"
    ]
}

现在,我有一个Json响应,如下所示,存储在movies.json文件中。

{
    "movieCategories": [
        "Animation",
         "Romance",
        "Science Fiction",
        "Western"
    ]
}

我不知道如何解析上面的json数组。请帮助。

谢谢。

4 个答案:

答案 0 :(得分:7)

假设

    var test = {
    "movieCategories": [
        "Animation",
         "Romance",
        "Science Fiction"
        "Western"
    ]
}

然后

test.movieCategories[0] // Will be Animation

答案 1 :(得分:3)

从这里下载json2.js https://github.com/douglascrockford/JSON-js 将其包含在您的网页上。 像这样使用

jsonobj = JSON.parse(jsonstring);
jsonstring = JSON.stringify(jsonobj);

答案 2 :(得分:1)

根据JSLint,这是无效的JSON。有一个“,”缺失:

{ "movieCategories": [ "Animation", "Romance", "Science Fiction", "Western" ] }

其余的请参阅:Is it possible to parse JSON with javascript?

答案 3 :(得分:1)

你只能使用像

这样的eval
<html>
<div>
<script language="javascript">
  var arr = '[{ "movieCategories": [ "Animation", "Romance", "Science Fiction" ,"Western" ] }]';
  var b = eval(arr)[0];
  alert(b.movieCategories);
</script>
</div>
</html>