访问从CMS返回的JSON数据

时间:2014-06-22 04:38:12

标签: javascript jquery json

我使用的CMS将为我提供数据库中每个项目的JSON数据。我使用以下代码来访问此数据:

var items = new BCAPI.Models.WebApp.ItemCollection("Strain Bank");
items.fetch({
  success: function (items) {
    items.each(function (item) {
        item.fetch({
            success: function (itemDetails) {
                console.log(JSON.stringify(itemDetails.attributes))
            }
        });
    });
  }
}); 

console.log(JSON.stringify(itemDetails.attributes))为每个项目输出以下代码。项目代码的示例如下:

{
    "id": 4441485,
    "name": "Alien OG",
    "fields": {
        "Buzz Length": "580",
        "Strength": "37",
        "Sativa Percentage": "231",
        "Overall Rating": "40",
        "Flower Time": "61",
        "Potency": "10",
        "Yield": "10",
        "Height": "20",
        "Reviews": "4",
        "Grow Reviews": "1",
        "Creative": "2",
        "Euphoric": "0",
        "Uplifted": "0",
        "Energetic": "2",
        "Lazy": "0",
        "Focused": "2",
        "Happy": "1",
        "Talkative": "0",
        "Giggly": "0",
        "Tingly": "0",
        "Hungry": "0",
        "Sleepy": "0",
        "Aroused": "0",
        "Migraines": "1",
        "Nausea": "0",
        "Insomnia": "0",
        "Pain": "2",
        "Anxiety": "0",
        "Stress": "2",
        "PMS": "0",
        "Lack of Appetite": "0",
        "Muscle Spasms": "0",
        "Depression": "2",
        "Seizures": "0",
        "Fatigue": "1",
        "Fruity": "0",
        "Citrus": "0",
        "Seasonings-Spicy": "1",
        "Floral": "2",
        "Pungent": "2",
        "Chemical": "1",
        "Earthy": "2",
        "Sweet": "0",
        "Grass": "1",
        "Skunky": "0"
    }
}

我需要做的是访问每个项目中的数据。我不确定该怎么做。我试过了:

//Thecode below replaces console.log(JSON.stringify(itemDetails.attributes)) in the above example.

var json = JSON.stringify(itemDetails.attributes)
$.each($.parseJSON(json), function(idx, obj) {
console.log(obj.name);
});

当我尝试上面的代码时,我在console.log中看到了两件事:

TypeError: obj is null

undefined

如何正确访问JSON数据?

2 个答案:

答案 0 :(得分:1)

您应该能够通过.表示法访问每个项目中的数据,例如itemDetails.attributes.iditemDetails.attributes.nameitemDetails.attributes.fields

替换如下:

console.log(JSON.stringify(itemDetails.attributes))

使用以下内容尝试

console.log(itemDetails.attributes.name);

答案 1 :(得分:0)

您正在错误地访问所需对象。尝试,

$.each(xObj.fields, function (key, val) {
    console.log(key + " : " + val);
});

DEMO