0

i have a json string returned to a hidden value and i want to assign it to a javascript array and print each element of the array.

Json string returned by hdn_client_windows - ["5703","5704"]

Javascript array assignment is as below.

var times = $('#hdn_client_windows').val();
alert(times[0]); // this printed only--> [
alert(times[1]); // this printed only--> "

what am i doing wrong ?

Tushar Gupta - curioustushar
57.2k24 gold badges106 silver badges110 bronze badges
asked Sep 30, 2013 at 9:29
1
  • As you said, it returns a JSON string - not an array object. Commented Sep 30, 2013 at 9:32

4 Answers 4

7

You need to parse the JSON into an array with JSON.parse first:

var times = JSON.parse($('#hdn_client_windows').val());

Since you are already using jQuery, it might be a good idea to defer to $.parseJSON instead just to be on the safe side (full compatibility with old browsers):

var times = $.parseJSON($('#hdn_client_windows').val());
answered Sep 30, 2013 at 9:31
Sign up to request clarification or add additional context in comments.

1 Comment

@Jon, Just added the link for the one who is not using jQuery. Direct link to JSON js library :)
3

Use $.parseJSON().

var str = '["5703","5704"]';
var times = $.parseJSON( str );
answered Sep 30, 2013 at 9:33

Comments

3

You have to parse the string first using JSON.parse (older browsers might require you to load this in):

var times = JSON.parse($('#hdn_client_windows').val());
alert(times[0]); // Will display first item
alert(times[1]); // Will display second item
answered Sep 30, 2013 at 9:31

1 Comment

Please fix/remove the comments from the code you've copied. There are few things that are worse than a misleading/wrong comment.
2

You could use jquery's parseJSON() function.

var str = '["5703","5704"]';
var parsed = $.parseJSON( str );

The parsed object now contains the array: ["5703","5704"]

Reference - jQuery.parseJSON( json )

"Takes a well-formed JSON string and returns the resulting JavaScript object."

answered Sep 30, 2013 at 9:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.