Nick
Nick

Reputation: 19664

Pull string value out of JSON object

I have a web service that returns me a JSON object that contains the string "Hello World". How do I pull this string out of the object?

data = [object Object]

Thanks

Nick

Upvotes: 3

Views: 1967

Answers (3)

JPrescottSanders
JPrescottSanders

Reputation: 2151

If you are using jQuery's post function you might follow this example found here.

$.post("test.php", { func: "getNameAndTime" },
    function (data) {
        alert(data.name); // John
        console.log(data.time); //  2pm
    }, "json");

In your case, I would suspect that you would call data.data.

Upvotes: 0

Andreas Grech
Andreas Grech

Reputation: 107950

You can either use eval:

var foo = eval('(' + data + ')');

But that is potentially dangerous, especially if you don't trust what is being sent from the server. Thus, the best way (and most secure way) to extract data from a JSON object is by using Crockford's JSON library:

var foo = JSON.parse(data);

Btw, if you're using jQuery to query ASP.Net Web Services, be careful of the the d. issue (which is used as a container object). Thus to extract the returned object, you have to do:

var foo = JSON.parse(data);
if (foo) {
    //Foo is not null
    foo = f.d;
}

More information about this here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

Upvotes: 2

mati
mati

Reputation: 5348

You have to know how is your object, what members the object have.

You could try something like

for(var e in data)
    alert(e + ' : ' + data[e]);

Upvotes: 6

Related Questions