Rob
Rob

Reputation:

How do I convert a JSON string to a JavaScript object in jQuery?

I have a string in my db I want to pull into my page and convert to a JavaScript object.

[
{id: 1,title: "Long Event",
       start: new Date(2009, 5, 6, 14, 0),end: new Date(2009, 5, 11)},
{id: 2,title: "Repeating Event",
       start: new Date(2009, 5, 2)},
{id: 3,title: "Meeting",
       start: new Date(2009, 5, 20, 9, 0)},
{id: 4,title: "Click for Facebook",
       start: new Date(2009, 5, 27, 16),end: new Date(2009, 5, 29),
       url: "http://facebook.com/"}
]

How can I do this using jQuery?

Upvotes: 32

Views: 66707

Answers (7)

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

The "official" json2.js script includes 2 methods: one that will safely parse any JSON string to an object (JSON.parse), and one that will convert an object to a JSON string (JSON.stringify)

The script can be found here.

In my post above, I suggested eval(), but there is actually a slightly better way to evaluate JSON (if you don't want to use the json2.js script):

var obj = (new Function("return " + json))();

using the json2.js script:

var obj = JSON.parse(json);

Upvotes: 7

bumperbox
bumperbox

Reputation: 10214

As of jQuery 1.4.1 you can do this natively

jQuery.parseJSON

See jQuery documentation.

Upvotes: 64

Alistair Evans
Alistair Evans

Reputation: 36473

While you can use the the eval command, you need to check it for safety first. I use:

var data = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.
           test(source.replace(/"(\\.|[^"\\])*"/g, '')))     
           && eval('(' + source + ')');

That should work (it's been adjusted a bit from the original). The key point is that the JSON string is checked to prevent functions and other actual executable code from sneaking through. (The first regex is the important bit).

That said, the JSON plugin is very good.

Upvotes: -1

knoopx
knoopx

Reputation: 17400

use

jQuery.getJSON(url, data, callback)

or pass "json" as the type parameter:

jQuery.get( url, data, callback, type )

same applies to:

jQuery.post( url, data, callback, type )

*all in case you are fetching the "string" from an ajax request

Upvotes: 0

andi
andi

Reputation: 14458

Did you look at the jquery-json plugin?

Upvotes: 1

Boris Guéry
Boris Guéry

Reputation: 47585

Take a look at JQuery-json plugin

var thing = {plugin: 'jquery-json', version: 1.3};

var encoded = $.toJSON(thing);              //'{"plugin": "jquery-json", "version": 1.3}'
var name = $.evalJSON(encoded).plugin;      //"jquery-json"
var version = $.evalJSON(encoded).version;  // 1.3

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

how about eval() ?

var obj = eval(jsonString);

Upvotes: 2

Related Questions