codingjoe
codingjoe

Reputation: 800

Get value from JSON string

I have the following JSON string:

{"d":"{\"Foo\":7,\"Bar\":5,\"Foobar\":3}"}

And the corresponding invocation in my js file:

$.getJSON("Foo.svc/GetSomeFoo", function (response) {
            alert(response["Foo"]);
            alert(response["Bar"]);
            alert(response["Foobar"]);
        });

Just trying to write out the values, but can't seem to get it out. It is probably very simple, but I am not finding anything helpful while googling it.

Upvotes: 1

Views: 16382

Answers (4)

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do this -

 alert(response.d.Foo);

Upvotes: 1

Dogbert
Dogbert

Reputation: 222040

Your JSON has embedded JSON. You need to do:

var d = JSON.parse(response.d);
alert(d.Foo);
...

Upvotes: 4

palaѕн
palaѕн

Reputation: 73886

Try this:

alert(response.d["Foo"]);

response gives you this: {"d":"{\"Foo\":7,\"Bar\":5,\"Foobar\":3}"}
response.d will give you: {\"Foo\":7,\"Bar\":5,\"Foobar\":3}
and finally response.d["Foo"] or response.d.Foo will give you: 7

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

Since you have an object named d as the outer object, you will need to get your data via it.

For ex: response.d["Foo"]

Upvotes: 1

Related Questions