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);
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);
The JSON.org website gives the simplest solution:
var y = eval('(' + x + ')');
Edit: Oh. Right. The eval
solution is good if and only if you are sure that you can trust the source to produce correct JSON objects. Otherwise, you will have to use a JSON parser - look at the other replies.
This paragraph fully covers the native JSON implementations, and libraries that use native JSON implementations: http://en.wikipedia.org/wiki/JSON#Native_JSON
Using native JSON implementation will be considerably faster/safer than using some javascript libraries for same task. However, if some library claims it will try using native implementation whenever possible - it's even better choice that using native JSON directly (compatibility and stuff).
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" );
you can also do the following which is slighly less evil than eval :) :
var x = '{ "id": 5, "name": "hello" }';
var y = new Function("return " + x)();
alert(y.id + " " + y.name);
tho as said by others, if you're using jquery, go for the inbuilt parseJson method.
cheers jim
Bruno,
here's the jquery method, which as you'll see, uses the self same new Function("return..) business.
parseJSON: function (a) {
if (typeof a !== "string" || !a) return null;
if (/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")))
return z.JSON && z.JSON.parse ? z.JSON.parse(a) : (new Function("return " + a))();
else c.error("Invalid JSON: " + a)
}
[edit] the regex is of course 'dealing' with any rogue characters embedded within ther json string.
spooky tho :)