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
try:
var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
alert(newJ.TeamList[0].teamname);
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))
Enclose the string in single quote it should work. Try this.
var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);
Combining Saurabh Chandra Patel's answer with Molecular Man's observation, you should have something like this:
JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}');
Quick answer, this eval work:
eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')
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"}]}'
Source: Stackoverflow.com