BrunoLM
BrunoLM

Reputation: 100381

How to convert a JSON string to an object?

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

Upvotes: 7

Views: 1810

Answers (7)

Josh Gallagher
Josh Gallagher

Reputation: 5329

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.

Upvotes: 0

jim tollan
jim tollan

Reputation: 22485

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.

Upvotes: 0

jim tollan
jim tollan

Reputation: 22485

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

Upvotes: 2

BalusC
BalusC

Reputation: 1109695

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" );

Upvotes: 9

Jean Hominal
Jean Hominal

Reputation: 16796

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.

Upvotes: 0

bezmax
bezmax

Reputation: 26142

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

Upvotes: 1

Aif
Aif

Reputation: 11220

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

Upvotes: 5

Related Questions