35

How do I convert string to object? I am facing this problem because I am trying to read the elements in the JSON string using "each".

My string is given below.

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

I have used eval and I have used

var obj = $.parseJSON(jsonObj);

And i have also used

var obj= eval("(" + jsonObj + ")");

But it comes null all the time

2
  • 1
    have you tried single quotes? '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}' Commented Feb 6, 2012 at 18:13
  • possible duplicate stackoverflow.com/questions/45015/… Commented May 8, 2013 at 7:53

7 Answers 7

71

Enclose the string in single quote it should work. Try this.

var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @ShankarSangoli. "$.parseJSON()" works fine. I was trying with "parseJSON()" which didn't really help.
18

Combining Saurabh Chandra Patel's answer with Molecular Man's observation, you should have something like this:

JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}');

Comments

11

try:

var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
    alert(newJ.TeamList[0].teamname);

1 Comment

Thank you very much for your code $.parseJSON(myjson) . It is really work.
4

Your string is not valid. Double quots cannot be inside double quotes. You should escape them:

"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"

or use single quotes and double quotes

'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'

Comments

4

only with js

   JSON.parse(jsonObj);

reference

Comments

3

Quick answer, this eval work:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')

Comments

1

Without eval:

Your original string was not an actual string.

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

The easiest way to to wrap it all with a single quote.

 jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'

Then you can combine two steps to parse it to JSON:

 $.parseJSON(jsonObj.slice(1,-1))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.