Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to JSON object

People also ask

How do I convert a 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?

To convert string to json in Python, use the json. loads() function. The json. loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements.

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.

How do you assign a JSON object to a string in Java?

JSONObject json= (JSONObject) JSONValue. parse(jsonData); JSONObject data = (JSONObject) json. get("data"); After you have parsed the json data, you need to access the data object later get "map" data to json string.


var obj = JSON.parse(string);

Where string is your json string.


You can use the JSON.parse() for that.

See docs at MDN

Example:

var myObj = JSON.parse('{"p": 5}');
console.log(myObj);

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

link:-

http://api.jquery.com/jQuery.parseJSON/


I had the same problem with a similar string like yours

{id:1,field1:"someField"},{id:2,field1:"someOtherField"}

The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized

var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)

Hope it helps,

If anyone has a more elegant approach please share.