0

This code fails

var data = '{ "name": "binchen" }';
data = JSON.stringify(data);
alert(data.name);//throws undifined 

This code works

 var data = { "name": "binchen" };              
 alert(data.name);

How do I convert data into an object in the first scenario?

1
  • 3
    Headline? JSON is a string - ALWAYS. If it's not a string it's not JSON. WHy are you trying to stringify a string??? Commented Jan 7, 2015 at 20:48

1 Answer 1

6

Use JSON.parse to parse the JSON string into a JavaScript object (there's no such thing as a "JSON object", JSON is a string based exchange format) :

data = JSON.parse(data);
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! I will mark it as soon as it lets me. Thank you !

Your Answer

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.