serializeJSON

Converts a ColdFusion variable into a JSON (JavaScript Object Notation) string.

serializeJSON(var [, serializeQueryByColumns, useCustomSerializer]) → returns String

Argument Reference for the serializeJSON function

var

Required: Yes
A ColdFusion variable.

serializeQueryByColumns

Required: No
Default: false
A Boolean value that specifies how to serialize ColdFusion queries.

useCustomSerializer

Required: No
Default: true

Compatibility

ColdFusion:

Version 8+ CF 11+ Added Application.cfc setting this.serialization.preserveCaseForStructKey which defaults to true, also added useCustomSerializer argument.

Links more information about serializeJSON

Examples sample code invoking the serializeJSON function


Serialize a Struct

Serialize a CF Struct into a JSON representation

person = {name="Pete Freitag", company="Foundeo"};
writeOutput( serializeJSON(person) );

Expected Result: {"COMPANY":"Foundeo","NAME":"Pete Freitag"}


Lower Case Keys

Same as above but they variable names are case sensitive by quoting them.

person = {"name"="Pete Freitag", "company"="Foundeo"};
writeOutput( serializeJSON(person) );

Expected Result: {"company":"Foundeo","name":"Pete Freitag"}


ACF Possible Issues

Adobe ColdFusion may incorrectly serializes some strings if they can be automatically converted into other types, like numbers or booleans. One workaround is to use a CFC with cfproperty to specify types. Another workaround is to prepend Chr(2) to the value and it will be forced to a string, however that is an unofficial / undocumented workaround.

person = { "phone"="123456789", "firstname"="no","lastname"="yes" };
writeOutput( serializeJson(person) );

Expected Result: {"phone":123456789,"firstname":false,"lastname":true}


Using setMetadata to force types

As of CF 2016.0.2+ (update 2) you can call setMetadata() as a member function on a struct to force a type

myStruct = {"zip"="00123"};
myStruct.setMetadata( { "zip": "String" } );
writeOutput(serializeJSON(myStruct));

Expected Result: {"zip":"00123"}


Fork me on GitHub