Liron Harel
Liron Harel

Reputation: 11247

Retrieve JSON Array element value

My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.

I've tried:

var a = msg.d[1].key

With no success of course.

This is the returned string:

"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"

The string was extracted using FireBug after watching the msg.d. Need your help in solving this.

Upvotes: 3

Views: 7721

Answers (3)

Peter Olson
Peter Olson

Reputation: 143017

msg[1].key

Assuming that the name of that array is msg. I'm not sure what you are using .d for.

If msg.d is a string representing an array, use JSON.parse.

JSON.parse(msg.d)[1].key

You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.

Upvotes: 6

Ray Toal
Ray Toal

Reputation: 88468

If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.

Upvotes: 0

bcurren
bcurren

Reputation: 74

This works as expected for me.

var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;

What is msg in the example above? Need more info to help.

Upvotes: 0

Related Questions