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?
-
possible duplicate of Serializing to JSON in jQueryoutis– outis2011年12月26日 10:09:43 +00:00Commented Dec 26, 2011 at 10:09
7 Answers 7
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);
1 Comment
JSON.parse(string) or JSON.stringify(object)how about eval() ?
var obj = eval(jsonString);
3 Comments
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
Comments
Did you look at the jquery-json plugin?
Comments
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
Comments
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.