开发者

Parsing JSON object in JQuery

开发者 https://www.devze.com 2022-12-19 06:59 出处:网络
I have simple JSON object returned in form {\"d\":\"{\\\"Name\\\":\\\"DMX100\\\",\\\"Description\\\":\\\"blah blah\\\",\\\"ID\\\":\\\" 780\\\",\\\"Make\\\":\\\"2010\\\"}\"}

I have simple JSON object returned in form

{"d":"{\"Name\":\"DMX100\",\"Description\":\"blah blah\",\"ID\":\" 780\",\"Make\":\"2010\"}"}

How do I parse it in success.

success: f开发者_JAVA百科unction(msg)                  
{                     
    $('#something').html(msg.d.Name);   
}

Above code doesnt display Name but when I pass $('#something').html(msg.d);

it shows complete JSON string. How do I reach to individual properties

Thanks


You don't need to eval - just use d.Name

(assuming d is a variable from msg.d)

It's also easy to iterate a json object that contains multiple 'rows' using jquery's .each method, as in this example:

$.each(msg.d, function() {      
    alert(this.SomeProperty);
});

And make sure you have set:

contentType: "application/json; charset=utf-8",
dataType: "json",

And finally, use firebug to console.log msg.d


If you use ajax(), you can set the dataType property to get JSON data. Manual


If you really want to eval it, here's how:

var data = eval("(" + msg + ")");


jQuery since 1.4 has special method to parse json, and from this version this one is not using eval but native parser.

Take a look here:

http://yehudakatz.com/2010/01/15/jquery-1-4-and-malformed-json/

and from jQuery documentation:

http://api.jquery.com/jQuery.parseJSON/


success: function(msg)
{
  injectHtml(msg.d);
}

function injectHtml(json) 
{
    //Get data from json
    var data = jQuery.parseJSON(json);
    var Name = Description = ID = Make = '';

    $.each(data, function() {
        Name = this.Name;
        Description = this.Description
        ID = this.ID;
        Make = this.Make;
    });

    //Inject 
    $('#something').html(Name);

}


Inject the Accepts header along with ContentType. This will notify the service that it needs the response in JSON and not as plaintext.

accepts: "application/json; charset=utf-8"

You can look up examples on how to eat this Request Header using jQuery AJAX.

Pass accepts header parameter to jquery ajax

0

精彩评论

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

关注公众号