Making Coldfusion sensitive to your (JSON) case

by

I inadvertently discovered that, contrary to popular belief and my own past experiences, ColdFusion can honor your variables’ case when using the built-in SerializeJSON.

First, the simple approach, which fails to produce most obvious results.

<cfscript>
 map = {};
 map.someNumber = 4;
 map.someString = "Hello JSON";
</cfscript>
<cfoutput>
 #SerializeJSON( map )#
<cfoutput>

This produces the following results. Notice that the keys (properties in JavaScript parlance) are UPPERCASED as though the serializer were shouting at you.

{"SOMENUMBER":4.0,"SOMESTRING":"Hello JSON"}

This becomes a problem when you deserialize the JSON in a case-sensitive context (i.e. JavaScript in a browser). It turns out this has little to do with the serialization and more to do with how ColdFusion creates struct keys from your (case-insensitive) code. We can help ColdFusion “do the right thing” by being more explicit with our keys.

Instead of creating a struct with variable names (which ColdFusion treats as case-insensitive), we’ll create struct keys with strings (which maintain their case.)

<cfscript>
 map = {};
 map[ "someNumber" ] = 4;
 map[ "someString" ] = "Hello JSON";
</cfscript>
<cfoutput>
 #SerializeJSON( map )#
</cfoutput>

This results in the following:

{"someNumber":4.0,"someString":"Hello JSON"}

Now we have no surprises when we consume this JSON in a browser. Our JavaScript object literals can use the same keys our CFML struct literals did.

Advertisements

One Response to “Making Coldfusion sensitive to your (JSON) case”

  1. Dan Watt Says:

    I faced a similar problem last week when dealing with some Hibernate / HQL in CF9. I was trying to just select a couple properties from an object, not the full object, and I was using the map() syntax in HQL, which in CF9 will return an array of Structs. I could not access the keys via the dot notation (map.key), but I was able to do map[‘key’].

    It would appear that internally a CF struct is just a java Map. If you use dot syntax, CF automatically converts the key to uppercase (map.key = map.KEY = map[‘KEY’]).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: