How can I convert a JSON string to an object in JavaScript? Is there a method that does this?
Something like:
var x = "{ id: 5, name: 'hello' }";
var y = /*something*/(x);
alert(y.id + " " + y.name);
Convert JSON String to JavaScript Object The JSON module offers two methods - stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.
Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.
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.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
As per the comments and question history it look like that you're already using jQuery. In that case, it's good to know that jQuery ships with a new parseJSON()
function since version 1.4.1 which was released late January this year. Consider upgrading if you're not at 1.4.1 yet. Here's an extract of relevance from its API documentation:
Description: Takes a well-formed JSON string and returns the resulting JavaScript object.
jQuery.parseJSON( json ) version added: 1.4.1
json The JSON string to parse.
Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:
{test: 1}
(test does not have double quotes around it).{'test': 1}
('test' is using single quotes instead of double quotes).Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from
parseJSON
. Where the browser provides a native implementation ofJSON.parse
, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.Example:
Parse a JSON string.
var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" );
Use json2 lib : http://www.json.org/js.html
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