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);
Share
Improve this question
edited Jun 11, 2010 at 12:09
BalusC
1.1m376 gold badges3.6k silver badges3.6k bronze badges
asked Jun 10, 2010 at 11:17
BrunoLMBrunoLM
100k86 gold badges308 silver badges460 bronze badges
7
|
Show 2 more comments
7 Answers
Reset to default 9As 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
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 :)
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).
The JSON.org website gives the simplest solution:
var y = eval('(' + x + ')');
More information
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.
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.
The modern answer to this question is to use JSON.parse
:
var myObject = JSON.parse(
'{ "id": 5, "name": "hello" }');
All modern browsers have this function built in, and most of them had it built in when the question was first asked.
eval
.) – kennytm Commented Jun 10, 2010 at 11:19