views:

190

answers:

6

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);
+5  A: 

Use json2 lib : http://www.json.org/js.html

Aif
A: 

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.

jhominal
Slow. Nothing more to say.
Max
@Max: XSS. ____
KennyTM
@KennyTM: Yes, forgot about that. Never used eval anyways...
Max
+1  A: 

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).

Max
+6  A: 

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 of JSON.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" );
BalusC
BalusC: I won't remove the `jquery` tag, but for future reference, the tags are for the *question*, not the answers. The question does not narrow the choices to jQuery, even if he is open to jQuery. Out of 6 answers, yours was the only jQuery related one. Basically, this is not a jQuery question and should not be tagged as such.
Blixt
A: 

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

jim
Nice one, but I guess this is as dangerous as `eval`
BrunoLM
Bruno - the mechanics under the covers are different and if you look at the jquery code, you may just see something akin to this in that function (parseJSON: function (a)). see excerpt below for jquery function from source..
jim
+1  A: 

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 :)

jim
but it uses JSON.parse where available, which is definitely a Good Thing (tm). Without the JSON object, there is hardly a better way to do the conversion, since making a full JSON parser in JavaScript would surely result in something slower than eval
ammoQ
ammoQ - yes, absolutely. just glad they didn't use the eval method as the fallback mind you :)
jim
It's safe because the regex, +1 for pointing it
BrunoLM