I am using JSON value to store in javascript array.

My JSON value :

"Users":[{"user_name":"User 1","id":1,"image_url":"/photos/list/missing.png","level":1,"position":{"name":"User ABC","description":"desc"}}]

I'm getting response in alert same as above. Code:

alert("Response : " + $.toJSON(res["Users"]));

O/P : Response : [{"user_name":"User 1","id":1,"image_url":"/photos/list/missing.png","level":1,"position":{"name":"User ABC","description":"desc"}}]

Storing this value as Code:

tempJSON = $.toJSON(res["Users"]);

alert("JSON Array : " + tempJSON.length); alert("Name : " + tempJSON[0]. user_name);

O/P : JSON Array : 132 -> No. of characters. Name : Undefined. -> Because it can't find value for "user_name"

If I'm Storing this value as Simple String. Code:

tempJSON = [{"user_name":"User 1","id":1,"image_url":"/photos/list/missing.png","level":1,"position":{"name":"User ABC","description":"desc"}}];

alert("JSON Array : " + tempJSON.length); alert("Name : " + tempJSON[0]. user_name);

Then Getting Exactly,

O/P :

JSON Array : 1 -> No. of Array.

Name : User 1

I don't getting what's going on. Please tell me any solution.

Thanks in advance.

share|improve this question

2  
It looks like the problem is that you're using the tempJSON as an object: tempJSON[0] will be the first character of the JSON string. If you need to access the object, you'll need to use res.Users[0] – steveukx Jul 11 at 7:20
steveukx : Thanks mate. Its working. – Manan Sheth Jul 11 at 7:29
feedback

2 Answers

I think the problem is

tempJSON = $.toJSON(res["Users"]);

=> you are getting a string in your tempJSON variable, not the object!

Maybe use firebug or any other developer tool to debug your JS.

share|improve this answer
Hey it's resolved by res.Users[0] value. It's working fine. May be it was consider whole value as a string. – Manan Sheth Jul 11 at 7:31
feedback

While fetching the value in tempJSON you don't have convert the object to JSON(String). Instead you try below code :-

var tempJSON = res["Users"];

For Your Reference:- try it out here

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.