tags:

views:

3837

answers:

7

I have a string in my db I want to pull into my page and convert to a json 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?

A: 

how about eval() ?

var obj = eval(jsonString);

Philippe Leybaert
Usually it's not a very good idea to use eval, unless there's absolutely no other way to achieve the objective at hand.
dalbaeb
You have a point, but the risk is minimal. Most of the time, you're evaluating JSON generated by your own server code, which is never a security risk?. Even jQuery does calls eval() to convert ajax JSON to an object.
Philippe Leybaert
Simplest solutions is best solution. If you know the source of JSON you are parsing, I think eval would be the best choice.
Thinker
A: 

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
Boris Guéry
A: 

Did you look at the jquery-json plugin?

andi
A: 

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

knoopx
+2  A: 

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: http://json.org/json2.js

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);
Philippe Leybaert
A: 

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.

Kazar
+2  A: 

as of jquery 1.4.1 you can do this natively

jQuery.parseJSON

http://api.jquery.com/jQuery.parseJSON/

bumperbox
Perfectly answers the OP's question.
mkoistinen