开发者

Parsing & accessing JSON data

开发者 https://www.devze.com 2023-02-22 14:35 出处:网络
I have JSON data (added a newline for readability) returned as [{\"pk\": 7, \"model\": \"pycourt_login.orders\", \"fields\": {\"status\":开发者_StackOverflow社区 0, \"delivered\": false, \"order_id\

I have JSON data (added a newline for readability) returned as

[{"pk": 7, "model": "pycourt_login.orders", "fields": {"status":开发者_StackOverflow社区 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, "transaction_id": "2008010661301935441", "quantity": 2}},
{"pk": 8, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "9count1%1", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:14", "dish": 9, "transaction_id": "2008010661301935454", "quantity": 1}}]

How do I access each item in jQuery.

I tried doing something like (assume that /pendingorders returns JSON)

$(document).ready(function (){ 
jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    success: function(json) {
        $.each(json.results, function(i,dish){
            alert(dish.pk); 
            },'json')
        },  
    }); 
});

This is the error I get in Firebug:

object is undefined
[Break On This Error] length = object.length,
jquery.js (line 605)


With the current structure, I think you just want:

jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    success: function(json) {
        $.each(json, function(i,dish){
              alert(dish.pk); 
        });
    }); 
});

You had a stray , 'json' as the third parameter to each, and a comma after the success value (which is okay but probably unintended)

However, you may want to make the top level an object instead of an array, due to JSON hijacking.

If the structure were:

{"results":
[{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, "transaction_id": "2008010661301935441", "quantity": 2}},
{"pk": 8, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "9count1%1", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:14", "dish": 9, "transaction_id": "2008010661301935454", "quantity": 1}}]}

your original each line:

$.each(json.results, function(i,dish){

would be correct.


You're passing 'json' as a parameter to each() (watch the indentation). You can usually do that on get(), but ajax() works differently - setting the dataType option should suffice:

jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    dataType: 'json',
    success: function(json) {
        $.each(json.results, function(i,dish){
            alert(dish.pk); 
        });
    }
});

See the ajax method documentation for reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消