无法使用jQuery解析json

时间:2015-06-11 20:22:55

标签: jquery json

我有这种json:

{
    "datas": [
        {
            "id": "001",
            "element": "#logo img",
            "category": "Test",
            "url": "http://example.com/test.html",
            "type": "file",
            "size": "10",
            "label": "Logo",
            "value": "aaaaaa"
        },
        {....

我尝试解析它,但它不起作用。

$.get('http://example.com/datas.json', function(data) {
    $.each(data, function(i, item) {
        alert(data[i].type);
    })
});

有人帮我吗?

3 个答案:

答案 0 :(得分:1)

您似乎错误地访问了数据。如果大括号是任何指示,data将是整个对象。你想要那个对象里面的数组。

$.get('http://example.com/datas.json', function(data) {
    $.each(data.datas, function(i, item) {
        alert(item.type);
    })
});

DEMO

var data = {
  "datas": [
    {
      "id": "001",
      "element": "#logo img",
      "category": "Test",
      "url": "http://example.com/test.html",
      "type": "file",
      "size": "10",
      "label": "Logo",
      "value": "aaaaaa"
    }
  ]
};

$.each(data.datas, function(i, item) {
  alert(item.type);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:0)

试试这个

 for(var prop in data) {
      if(data.hasOwnProperty(prop)) {
         console.log(data[prop]['type'];
      }
    }

答案 2 :(得分:0)

尝试使用$.get('http://example.com/datas.json', function(data) { var parsed = $.parseJSON(json); console.log(parsed); });

https://jsfiddle.net/scheda/ehzj7qb3/

{{1}}