Converting a JSON string into a javascript object

Posted on Monday, September 27th, 2010 at 7:01 am

I’ve been working on a side-project recently that is utilizing the extJs library. At one point I am populating an extJs grid with a set of JSON data built in a Coldfusion function. 99% of the time I would simply return my JSON as ‘JSON’ using the ‘returnFormat’ attribute of the cffunction tag. But because I’m building this to work with CF7 as well as above and beyond I am having to return the JSON from the function to the calling page as a string that is built manually. It is retrieved using AJAX.

As far as javascript is concerned the JSON string is just a string. It needs to be deserialized into a javascript object whose name/value pairs become readily available for use. One way to do this is to use the javascript eval() function. I’ve illustrated an example below.

Will not work as a string

var jsonDataString = '{docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]}';

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataString,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

Will work as an object

var jsonDataString = '{docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]}';
var jsonDataObject = eval('(' + jsonString + ')');

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataObject,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

Will also work if writing JSON in javascript as an object

var jsonDataObject = {docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]};

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataObject,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

In the first example our JSON data is stored and read as a string. This will not work when it comes time to parse it since it isn’t an object. In the second example, that same string is evaluated as an object using the ‘eval()’ method to type the string as an object.

In the last example I simply wanted to show that if you are writing the JSON within javascript to begin with there is no need to use the eval() method since you can write the JSON without the single-quotes and it will be immediately typed as an object.

Tags
CategoryJavascript

Leave a Reply

*
(Won't be published) *