ColdFusion serializeJSON Problem

I ran into a little problem with the CF8 serializeJSON function. The function doesn’t properly escape quotes in struct keys, which results in invalid JSON being generated.

For Example: (all code is in cfscript)

// Struct Key with quotes in it
heightCounts["6'0"""] = 5;

// Serialize function runs alright...
serialized = serializeJSON(heightCounts);

// But the JSON is invalid. The quotes are unescaped! 
writeOutput(serialized);
// => {"6'0"":5.0}

// As you might expect, deserializing throws an error
deserializeJSON(serialized);

I certainly don’t like the idea of having quotes in struct keys, but that’s beside the point. I filed a bug report, but I also wrote a little function to jsStringFormat my struct keys. Problem solved!

function cleanKeys(dirtyData) {
	var cleanData = structNew();
	var cleanKey = "";
	var i = "";

	if(!isStruct(dirtyData)) {
		return dirtyData;
	}

	for(i in dirtyData) {
		cleanKey = jsStringFormat(i);
		cleanData[cleanKey] = cleanKeys(dirtyData[i]);
	}

	return cleanData;
}

You just pass in your quote-fully keyed struct, and get a clean one back:

// Same example as above
heightCounts["6'0"""] = 5;

// This time we sanitize the struct keys
jsSafeHeightCounts = cleanKeys(heightCounts);

// The serializeJSON call still runs without error
serialized = serializeJSON(jsSafeHeightCounts);

// But this time the output is correct!
writeOutput(serialized);
// => {"6'0"":5.0}

// And the deserialize works as expected
deserializeJSON(serialized);

Ta Da!