2

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
  • Clarify - are you using .html with msg.d.Name or msg.d ? Commented Feb 1, 2010 at 15:38
  • 1
    Install firebug for firefox and console.log(msg.d) - so you can make sure your object isn't being escaped by the .net method. Commented Feb 1, 2010 at 16:21
  • Did you manage to resolve the issue ? I am also having the same problem. Commented Sep 12, 2012 at 14:33

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

Comments

1

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

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

Comments

0

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/

1 Comment

I have eval as commented line..sorry for the confuson up there. still couldnt parse it.
0
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);

}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.