Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a JSON string to a JavaScript object in jQuery?

People also ask

Can JSON be converted to JavaScript?

JSON text/object can be converted into Javascript object using the function JSON. parse(). If we pass a invalid JSON text to the function JSON. parse(), it will generate error (no output is displayed when using in tag of HTML).

Which method convert JSON data to JavaScript?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

How can I convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


As of jQuery 1.4.1 you can do this natively

jQuery.parseJSON

See jQuery documentation.


The "official" json2.js script includes 2 methods: one that will safely parse any JSON string to an object (JSON.parse), and one that will convert an object to a JSON string (JSON.stringify)

The script can be found here.

In my post above, I suggested eval(), but there is actually a slightly better way to evaluate JSON (if you don't want to use the json2.js script):

var obj = (new Function("return " + json))();

using the json2.js script:

var obj = JSON.parse(json);

how about eval() ?

var obj = eval(jsonString);


Take a look at JQuery-json plugin

var thing = {plugin: 'jquery-json', version: 1.3};

var encoded = $.toJSON(thing);              //'{"plugin": "jquery-json", "version": 1.3}'
var name = $.evalJSON(encoded).plugin;      //"jquery-json"
var version = $.evalJSON(encoded).version;  // 1.3

Did you look at the jquery-json plugin?