Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to JSON Object

Tags:

json

jquery

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

like image 349
jith10 Avatar asked Feb 06 '12 18:02

jith10


People also ask

Can we convert string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.

How do you convert a string to a JSON object in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

Can we convert JSONArray to JSON object?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

Can we convert string to object in Java?

We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required.


2 Answers

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

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

Demo

like image 132
ShankarSangoli Avatar answered Sep 18 '22 19:09

ShankarSangoli


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

JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'); 
like image 30
Arnold Avatar answered Sep 17 '22 19:09

Arnold