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

jww
  • 97,681
  • 90
  • 411
  • 885
jith10
  • 553
  • 3
  • 11
  • 17

7 Answers7

70

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

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

Demo

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 1
    Thanks @ShankarSangoli. "$.parseJSON()" works fine. I was trying with "parseJSON()" which didn't really help. – simplysiby Jul 12 '18 at 04:17
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"}]}');
Community
  • 1
  • 1
Arnold
  • 311
  • 4
  • 9
11

try:

var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
    alert(newJ.TeamList[0].teamname);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
4

only with js

   JSON.parse(jsonObj);

reference

Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
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"}]}'
Molecular Man
  • 22,277
  • 3
  • 72
  • 89
3

Quick answer, this eval work:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')
Simon Edström
  • 6,461
  • 7
  • 32
  • 52
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))
Chad
  • 11
  • 2