tags:

views:

478

answers:

5

Hi, 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: function(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

+3  A: 

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

ScottE
Hi ScottE,I am not using eval, It's a commented line should get rid of it to avoid confusion.
A: 

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

Pekka
dataType is already set to JSON.
A: 

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/

bluszcz
I have eval as commented line..sorry for the confuson up there.still couldnt parse it.
A: 

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

var data = eval("(" + msg + ")");
Mike Robinson
A: 
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);

}
amelvin