<<

Data Handling

JSON

By Dave Ferguson (Bio)
gist

JSON or, JavaScript Object Notation, is a simple way for applications to share data. It is commonly used to send data from a server to a browser client, but it can be used for much more. It closely resembles XML without the markup or, more accurately, a struct of structs. Creating JSON data in ColdFusion is just about as easy as setting a variable.

Create JSON String

To create JSON, you first need to start with a structure. For example:

Structure:

<cfset myStruct = {
    items: {
        item1:  {name: 'something', price: 1000},
        item2:  {name: 'something else', price: 12.50},
        item3:  {name: 'something more', price: "1,240.10"}
    },
    users: {
        user1:  {id: 1, email: 'none@none.net'},
        user2:  {id: 2, email: 'none@none.net'},
        user3:  {id: 3, email: 'none@none.net'}
    }
} />

Then convert it to JSON

<cfset myJsonVar = serializeJSON(myStruct) />

End Result:

{"USERS":{"USER3":{"ID":3,"EMAIL":"none@none.net"},"USER2":{"ID":2,"EMAIL":"none@none.net"},"USER1":{"ID":1,"EMAIL":"none@none.net"}},"ITEMS":{"ITEM2":{"PRICE":12.50,"NAME":"something else"},"ITEM3":{"PRICE":"1,240.10","NAME":"something more"},"ITEM1":{"PRICE":1000,"NAME":"something"}}}

Notice, however, that all the names in the name/value pairs have been converted to uppercase. This is default behavior, but it can be easily remedied. It is caused by how the structure is created. If we alter the structure creation to the following, the names will not change case:

"items": {
    "item1":    {name: 'something', price: 1000},
    "item2":    {name: 'something else', price: 12.50},
    "item3":    {name: 'something more', price: "1,240.10"}
},

Any name that needs to remain in lower cause would need to be quoted. Leaving it uppercase is just fine, but remember that if the JSON data is being used by JavaScript, then be careful as JS is case sensitive.

Convert JSON to Structure

Converting a JSON string to a ColdFusion structure requires one single function:

<cfset myJsonStruct = deserializeJSON(myJsonVar) />

Validate String as JSON

Checking to see if a string is in a valid JSON format is simple as well. All it takes is a call to a validator function:

<cfdump var="#isJson(myJsonVar)#" />