我想我是傻瓜......但是我无法正确获取我的JSON输出

时间:2012-03-21 21:35:25

标签: jquery getjson json

我正在尝试建立一个购物车。

这是一个非常简单的类,可以创建一个包含我的购物车项目的generic.dictionary(of string, generic.dictionary(of string, string)

初始词典的键是项目ID,因此我可以使用cartDictionary.ContainsKey(id)轻松检查项目是否已经在购物车中,然后根据需要增加数量或添加新项目。

BUY按钮触发和AJAX-ified web方法,返回如下所示的数据:

{
    "d": {
        "7907": {
            "id": "7907",
            "qty": "4",
            "singlePrice": "1185"
        },
        "2698": {
            "id": "2698",
            "qty": "1",
            "singlePrice": "1322"
        }
    }
}

初始项目d由AJAX帖子自动创建,原因我不明白,但它并不重要,因此我的输出在我的AJAX成功data.d中如下:

success: function (data) {
    result = [data.d];
}

现在,我需要能够将内部数据呈现给购物车

所以我需要能够通过ID遍历项目并提取

id
qty
singlePrice

这样我就可以在浏览器中显示它了,但是我正试图解决这个问题。

我尝试在data.d周围添加[,例如

var result = [data.d]

并尝试在结果中循环,如

result = [data.d];

    $(result).each(function (i, thing) {
         var thisOne = (result[i]);
         //alert(thing); //<< returns object object
         $(thisOne).each(function (j, val) {
              alert(thisOne + " - " + val.id); //<< both thisOne and val.id return object object
         });
     });

通过警报返回我正在清理某些JSON对象,但我显然有些混淆了!

我不是程序员,但正在开展一个让我疯狂的项目!!

4 个答案:

答案 0 :(得分:1)

你应该做

var data = {
    "d": {
        "7907": {
            "id": "7907",
            "qty": "4",
            "singlePrice": "1185"
        },
        "2698": {
            "id": "2698",
            "qty": "1",
            "singlePrice": "1322"
        }
    }
}



var result = data.d;

$.each(result , function(ind, el) {
    //alert(thing); //<< returns object object
    alert(ind + " - " + el.id);
});

在这里摆弄http://jsfiddle.net/VHPQX/

答案 1 :(得分:1)

success: function (data) {
    var d = $.parseJSON(data.d);
    for(var i =0;i<d.length;i++)
    {     
        alert("Id is"+d[i].id);
    }
}

答案 2 :(得分:0)

你需要使用jQuery的generic iterator $.each()而不是它的jQuery对象迭代器$().each()

success: function (data) {
    $.each(data.d, function(k, val) {
       // "val" is the current item, so use its properties here, e.g.:
       var id = val.id,
           total = +val.qty * +val.singlePrice;
    });
}

(简单演示:http://jsfiddle.net/2vvfZ/

请注意,当迭代对象的属性时,订单无法保证(当我在Chrome中测试它时,它会执行2698项目,然后是7907项目)。如果您需要确定订单使用对象数组。

答案 3 :(得分:0)

你可以使用for..in循环:

for (key in data.d)
{
    document.write(key + '<br>')
    document.write('<blockquote>')
    document.write('id: ' + data.d[key].id + '<br>')            
    document.write('qty: ' + data.d[key].qty + '<br>')            
    document.write('singlePrice: ' + data.d[key].singlePrice + '<br>')            
    document.write('</blockquote>')
}

结果:

2698
    id: 2698
    qty: 1
    singlePrice: 1322
7907
    id: 7907
    qty: 4
    singlePrice: 1185

JSFiddle:http://jsfiddle.net/qnqWK/