admin管理员组

文章数量:1398832

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 ma. 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.

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 ma. 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.

Share Improve this question edited Aug 14, 2011 at 17:25 Liron Harel asked Aug 14, 2011 at 17:18 Liron HarelLiron Harel 11.2k27 gold badges123 silver badges223 bronze badges 5
  • And what is msg.d? The JSON string? – Felix Kling Commented Aug 14, 2011 at 17:20
  • 2 @Felix: OP must be using ASP.NET which wraps JSON returns in .d – codeandcloud Commented Aug 14, 2011 at 17:22
  • Yes it is, it represents the JSON string which the web service returns after JSON serialization in C#. I'm developing in ASP.NET and JQuery, – Liron Harel Commented Aug 14, 2011 at 17:22
  • Show the surrounding code. We need to know what msg.d is like Felix says and also whether you ever called JSON.parse or not. :-) – Ray Toal Commented Aug 14, 2011 at 17:23
  • posted the returned string (just shorten it because it was much longer) – Liron Harel Commented Aug 14, 2011 at 17:26
Add a ment  | 

3 Answers 3

Reset to default 6
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.

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.

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

本文标签: javascriptRetrieve JSON Array element valueStack Overflow