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
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.
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.
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.
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.
Enclose the string in single quote it should work. Try this.
var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'; var obj = $.parseJSON(jsonObj);
Demo
Combining Saurabh Chandra Patel's answer with Molecular Man's observation, you should have something like this:
JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With