开发者

Parsing JSON with JQuery

I have some JSON that looks like the following:

[{
    "Age": 35,
    "FirstName": "Peyton",
    "LastName": "Manning"
  },
  {
    "Age": 31,
    "FirstName": "Drew",
    "LastName": 开发者_JS百科"Brees"
  },
  {
    "Age": 58,
    "FirstName": "Brett",
    "LastName": "Favre"
  }
]

This JSON is passed into a function I have created called parseJSON. This function looks like this:

function parseJSON(result)
{
  $.each(result.items,function(i,item) {
    alert("First Name: " + item.FirstName);
    alert("Age: " + item.Age);
  });
}

When I run this code though, I get a JavaScript error that says "G is undefined". How do I parse my JSON with JQuery such that I can read the FirstName and Age properties?

Thank you!


Most simple parse JSON by native JS:

function parseJSON(result)
{
  for(var i in result) {
    var item = result[i];
    alert("First Name: " + item.FirstName);
    alert("Age: " + item.Age);
  } 
}


Here is a working function that uses your sample case.

var result = [{
    "Age": 35,
    "FirstName": "Peyton",
    "LastName": "Manning"
}, {
    "Age": 31,
    "FirstName": "Drew",
    "LastName": "Brees"
}, {
    "Age": 58,
    "FirstName": "Brett",
    "LastName": "Favre"
}];

function parseJSON(result){
    $.each(result, function(index, object){
        $.each(object, function(i, o){
            alert(i + " = " + o);
        })
    })
}

parseJSON(result);


Check your complete code, not only the sample shown here for "G". I suppose, there is a syntax error somewhere. As to the use of "result" - it could be a global variable, but tvanfosson is right I think. Doesn't look good here.


From json.org: json_sans_eval. This parses a JSON string without the hazards of using eval.


You are using a variable called result that doesn't exist in your function. Perhaps, it should be replaced with json.

function parseJSON(json) 
{ 
  $.each(json,function(i,item) { 
    alert("First Name: " + item.FirstName); 
    alert("Age: " + item.Age); 
  }); 
}

EDIT: based on your update, I think it's because you are referencing a property on result that doesn't exist, namely items. The null value being passed into the each function is causing jQuery to choke on an internal function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜