Converts ColdFusion data into a JSON (JavaScript Object Notation) representation of the data.


A string that contains a JSON representation of the parameter value.



SerializeJSON(var[, serializeQueryByColumns[, useSecureJSONPrefix[, useCustomSerializer]]])

See also

DeserializeJSONIsJSONcfajaxproxyUsing data interchange formats in the Developing ColdFusion Applications


ColdFusion (2016 release) Update 2: Added support for struct and array serialization using getMetadata.

ColdFusion 11: Added new attributes: useSecureJSONPrefix and useCustomSerializer.

ColdFusion 8: Added function





A ColdFusion data value or variable that represents one.


This parameter can be a Boolean value that specifies how to serialize ColdFusion queries or a string with possible values "row", "column", or "struct".


False by default. When Prefix Serialized JSON is enabled in the ColdFusion Administrator, then by default this function inserts the secure json prefix at the beginning of the json.


true/false. Whether to use the customSerializer or not. The default value is true. Note that the custom serialize will always be used for serialization. If false, the JSON serialization will be done using the default ColdFusion behavior.


This function is useful for generating JSON format data to be consumed by an Ajax application.The SerializeJSON function converts ColdFusion dates and times into strings that can be easily parsed by the JavaScript Date object. The strings have the following format:

MonthName, DayNumber Year Hours:Minutes:Seconds

The SerializeJSON function converts the ColdFusion date time object for October 3, 2007 at 3:01 PM, for example, into the JSON string "October, 03 2007 15:01:00".The SerializeJSON function with a false serializeQueryByColumns parameter (the default) converts a ColdFusion query into a row-oriented JSON Object with the following elements:




An array of the names of the columns.


A two-dimensional array, where:

  • Each entry in the outer array corresponds to a row of query data.
  • Each entry in the inner arrays is a column field value in the row, in the same order as the COLUMNS array entries.

For example, the SerializeJSON function with a serializeQueryByColumns parameter value of false converts a ColdFusion query with two columns, City, and State, and two rows of data into following format:

{"COLUMNS":["CITY","STATE"],"DATA":[["Newton","MA"],["San Jose","CA"]]}

The SerializeJSON function with a serializeQueryByColumns parameter value of true converts a ColdFusion query into a column-oriented JSON Object that is equivalent to the WDDX query representation. The JSON Object has three elements:




The number of rows in the query.


An array of the names of the columns.


An Object with the following:

  • The keys are the query column names
  • The values are arrays that contain the column data

For example, the SerializeJSON function with a serializeQueryByColumns parameter value of false converts a ColdFusion query with two columns, City, and State, and two rows of data into following format:

{"ROWCOUNT":2, "COLUMNS":["CITY","STATE"],"DATA":{"City":["Newton","San Jose"],"State":["MA","CA"]}}


The SerializeJSON function generates an error if you try to convert binary data into JSON format.

The SerializeJSON function converts all other ColdFusion data types to the corresponding JSON types. It converts structures to JSON Objects, arrays to JSON Arrays, numbers to JSON Numbers, and strings to JSON Strings.


ColdFusion internally represents structure key names using all-uppercase characters, and, therefore, serializes the key names to all-uppercase JSON representations. Any JavaScript that handles JSON representations of ColdFusion structures must use all-uppercase structure key names, such as CITY or STATE. You also use the all-uppercase names COLUMNS and DATA as the keys for the two arrays that represent ColdFusion queries in JSON format.

This example creates a JSON-format data feed with simple weather data for two cities. The data feed is in the form of a JavaScript application that consists of a single function call that has a JSON Object as its parameter. The example code does the following:

  1. Creates a query object with two rows of weather data. Each row has a city, the current temperature, and an array of forecast structures, with each with the high, low, and weather prediction for one day. Normally, datasource provides the data; to keep the example simple, the example uses the same prediction for all cites and days.

  2. Converts the query to a JSON format string and surrounds it in a JavaScript function call.

Writes the result to the output.
If you view this page in your browser, you see the resulting JavaScript function and JSON parameter. To use the results of this page in an application, put this file and the example for the DeserializeJSON function in an appropriate location under your ColdFusion web root, replace the URL in the DeserializeJSON example code with the correct URL for this page, and run the DeserializeJSONexample.

<!--- Generate a clean feed by suppressing white space and debugging
information. --->
<cfprocessingdirective suppresswhitespace="yes">
<cfsetting showdebugoutput="no">
<!--- Generate the JSON feed as a JavaScript function. --->
<cfcontent type="application/x-javascript">

// Construct a weather query with information on cities.
// To simplify the code, we use the same weather for all cities and days.
// Normally this information would come from a data source.
weatherQuery = QueryNew("City, Temp, Forecasts");
QueryAddRow(weatherQuery, 2);
theWeather.Weather="Partly Cloudy";
for (i=1; i<=5; i++) weatherArray[i]=theWeather;
querySetCell(weatherQuery, "City", "Newton", 1);
querySetCell(weatherQuery, "Temp", "65", 1);
querySetCell(weatherQuery, "ForeCasts", weatherArray, 1);
querySetCell(weatherQuery, "City", "San Jose", 2);
querySetCell(weatherQuery, "Temp", 75, 2);
querySetCell(weatherQuery, "ForeCasts", weatherArray, 2);

// Convert the query to JSON.
// The SerializeJSON function serializes a ColdFusion query into a JSON
// structure.
theJSON = SerializeJSON(weatherQuery);

// Wrap the JSON object in a JavaScript function call.
// This makes it easy to use it directly in JavaScript.
writeOutput("onLoad( "&theJSON&" )");

ColdFusion 11 has enhanced the JSON serialization to support the following new features:

  1. Case preservation of struct keys

  2. Data type preservation

  3. Key-value serialization  of CF Query

  4. Custom serializers

Case preservation of struct keys

Currently, the cases for struct keys are not preserved in ColdFusion. The struct keys get converted to upper case automatically.

For instance, consider the following code:

data = {empName="James", age="26"};
serializedStr = serializeJSON(data);

In ColdFusion 10 and earlier vesions, the output generated by the above code will be:

{'EMPNAME'='', 'AGE'=''}

For the release after ColdFusion 11, the output generated will be:

{'empName'='', 'age'=''}

To enable case preservation of struct keys at the application level, modify the application.cfc file by setting:

this.serialization.preservecaseforstructkey = true


Key preservation do not work on keys in application, session, or request scopes.

The default behavior is true. To switch back to the old behavior, set this value to false.

To  enable case preservation of struct keys at the server level, perform the following tasks:

  1. From the ColdFusion Administrator page, click Server Settings > Settings
  2. Click Preserve case for Struct keys for Serialization

Note that this setting is used during compilation of the CFML page and therefore if this flag is changed (in the administrator or programmatically), any pages relying on the change must be recompiled. This is done typically by simply editing the file (make any change at all) and re-executing it. If "trusted cache" is enabled in the ColdFusion Administrator, you must clear the template cache (of at least those affected files), which can also be done from within the ColdFusion Administrator Caching page.

Data type preservation

The ColdFusion language is typeless and does not evaluate or preserve the type information at the time of code generation. At runtime, ColdFusion tries to make its best guess to determine the datatype, which may cause some unexpected behavior. For example, at the time of JSON serialization, ColdFusion attempts at converting a string to a number. If the attempt is successful, then the passed data type is treated as number irrespective of whether you wanted it to be a string or not.

Starting from ColdFusion 11, the data type is preserved during the code execution time for Query and CFCs.

SerializeJSON considers datatypes defined in the database for serialization. If the database defines a column as a string, any number inserted into the column will still be treated as a string by SerializeJSON.

For instance,

<cfquery name="qry_Users" datasource="#DSN#">
select * from users

Serializing query

SerializeJSON honors the datatypes of columns defined in the database. The same would work for in-memory queries created using QueryNew() as long as the datatype is specified for the columns. 

Consider the CFC property type example:


Component accessors="true"
property string empName;
property numeric age;
property string dept;


emp = new Employee({empName="James", age=26, dept="000"});

OUTPUT: {"dept":"000","empName":"James","age":26}

In the previous version of ColdFusion, 000 will be automatically coverted to a number at runtime.

Additional format for query serialization

ColdFusion 10 supports 2 different ways to serialize a query object to a JSON string:

  • Using row
  • Using column

However, these 2 types are not the easiest to use with AJAX applications. ColdFusion 11 introduces a new way to serialize a query object to a JSON string:

  • Using struct

All the 3 ways, can be defined at the application-level and will be used in serialized JSON functions if the type is not defined explicitly. In application.cfc, define:

this.serialization.serializeQueryAs = [row|column|struct]

Note that "struct" is also available to be accessible through an AJAX argument. Now you can pass struct  in an AJAX URL to serialize a query object as struct.

ColdFusion 11 now supports serializing the query object to a JSON string that is AJAX-friendly:


The current SerializeJSON function has been enhanced to support the 'key-value' format.

SerializeJSON( Object o, Object serializeQueryByColumns, boolean secure, boolean useCustomSerializer);

If you are using the serialzeQueryAs property in application.cfc, you do not need to specify the serialzeQueryByColumns property unless you need to override the functionality.

Custom serializers

In the application.cfc file, you can register your own handler for serializing and deserializing the complex types. If the serializer is not specified, ColdFusion uses the default mechanism for serialization. For more information see Support for pluggable serializer and deserializer.

Serializing structs

Adobe ColdFusion (2016 release) Update 2 enables you to specify the datatype information for keys in a struct. This is known as metadata.

Before you get started on setting the metadata, familiarize yourself with the attributes used in a metadata. The table below lists the metadata attributes:

Attribute Description
Type The datatype of the struct key.
Name While serializing a key in a struct, instead of using the key name as JSON key, the specified name in this is used.


A struct that contains metadata information for nested structs.


Array of datatypes when setting the metadata for serializing elements in arrays or arrays inside structs.


When “true”, ignores specified keys in struct. Default is “false”.

       example = structnew();
       example.firstname = "Yes";
       example.lastname = "Man";
       // Default serialization converting ctring Yes to true

In the output below, you can see that the value of the key FIRSTNAME has been serialized to true (Boolean value), due to the absence of information on datatype.


Use the struct function, setMetadata, to specify the metadata.

The metadata is a struct where each key is struct key and the value of each key specifies the information on how to serialize in JSON.

The value of the key can be a string or a struct.

Value as string

metadata = {firstname: "string"}};

Value as struct

metadata = {firstname: {type: "string"}};

The datatype values are string, numeric, integer, boolean, date, array, and struct.

       example = structnew();
       example.firstname = "Yes";
       example.lastname = "Man";
       // changing the default serialization by specifying the type of "firstname" as string
       metadata = {firstname: {type:"string"}};

You can see that the value of the key FIRSTNAME is "Yes", which is the desired output.


In addition to passing the type info at struct level, you can also define the metadata in Application.cfc, as shown below:

this.serialization.structmetadata={firstname: {type:"string",name:"fname"},lastname:{name:"lname"}};

If defined as above, you need not define the datatype for firstname for the values that contains this key. For more information, see Application.cfc variables.


At runtime, if the metadata of the struct is not passed at struct level but is defined at the application level, then the application-level metadata is used for serializing the struct.  But if you define the metadata in the struct, then the metadata at struct level takes priority over the one defined in Application.cfc

When you serialize a struct to JSON, the struct keys always appear in upper case. You can change this by specifying the exact name of the key in the struct, as shown below:

       example = structnew();
       example.firstname = "Yes";
       example.lastname = "Man";
       writeoutput("<b>After serialization</b>:");
       // change the JSON key firstname to fname 
       metadata = {firstname: {type:"string",name:"fname"}};

In the output below, you can see the the key FIRSTNAME has changed to fname.


If the metadata is not specified for a key in the struct, default serialization is applied.

Serialization in nested structs

A struct can have nested structs. There are two ways of specifying the metadata for a key whose value is a struct.

Setting the metadata of a struct key on the parent struct

Specify the metadata for a key whose value is a struct in a struct. The struct can contain the metadata for the keys existing in the nested struct. If you do not specify the metadata for such key asstruct, the ColdFusion checks if there is any metadata set explicitly on the nested struct. If yes, the metadata in the nested struct is honored and is used for serializing the nested struct.

If there is no metadata in both nested struct and parent struct, then ColdFusion default serialization is applied for the nested structs.

For example,

       employee = structnew();
       // define the struct key-value pairs
       employee.firstname = "Yes";
       employee.lastname = "Man";
       // define a nested struct for the key address
       employee.address = {"doorno": "148", "street":"10 Down Street", "country": "UK"};
       metadata = {firstname: {type: "string", name: "fname"}, address: {keys:
       // set the metadata for a key in the nested struct
             "doorno": {type: "string", name: "DoorNo"},
             "street": "string",
             "country": "string"

The output is:

{"LASTNAME":"Man","ADDRESS":{"country":"UK","DoorNo":"148","street":"10 Down Street"},"fname":"Yes"}

The above situation is beneficial when, for example, an employee struct contains a physical address. The DoorNo key, in the above example, is specified as 148. But the DoorNo key can also contain alphanumeric values (148a,148-a, and so on). In such cases, the example above serializes the DoorNo key as string.

{"LASTNAME":"Man","ADDRESS":{"country":"UK","DoorNo":"148-a","street":"10 Down Street"},"fname":"Yes"}

Set the metadata for the key DoorNo as string. The metadata for the inner struct should be specified as a struct and should be in a key called keys. 

Setting metadata on the nested struct using setMetadata function

If both parent and nested structs have metadata, then the parent's metadata is considered for serialization. For example,

       employee = structnew();
       employee.firstname = "Yes";
       employee.lastname = "Man";
       employee.address = {"doorno": "148", "street":"10 Downing Street", "country": "UK"};
       employee.address.setmetadata({"doorno": {type: "string", name: "DoorNo"},"street": "string","country": "string"});
       // changing the default serialization by specifying the type of firstname as string and
       // changing JSON key firstname to fname
       metadata = {firstname: {type: "string", name: "fname"}};

The output is:

{"LASTNAME":"Man","ADDRESS":{"country":"UK","DoorNo":"148","street":"10 Downing Street"},"fname":"Yes"}

When serializing the address key in the employee struct and if the employee struct does not have any metadata for it, CodlFusion checks if there is any metadata set in the address struct. If there is metadata defined, the metadata is utilized for serialization, else default serialization happens.

Serializing an array inside a struct

A ColdFusion struct can contain an array representing a key. The array can contain values of different datatypes.

If the elements in the array have the same type, specify the datatypes as a struct with the keys having the values of the datatype. For example,

{title: {type:"string",name:"title"}, tags:{items:"string",name:"keywords"}};

The code sample below illustrates serialization of an array inside a struct.

       blogPost = structnew();
       blogPost.Title = "Struct Serialization";
       blogPost.referenceURL = "";
       // define an array for a struct key. In the array all elements are of type string, except 2016
       blogPost.tags = ["struct", "json", "serialization", "2016", "HF2", "metadata"];
       // specify all elements as string in the metadata
       metadata = {title: {type: "string", name: "title"}, tags: {items: "string", name: "keywords"},referenceURL:{name:"url"}};

The output using default JSON serialization is as follows:

{"TITLE":"Struct Serialization","TAGS":["struct","json","serialization",2016,"HF2","metadata"],"REFERENCEURL":""}

All values inside the TAGS array get serialized as string except 2016 which gets serialized as numeric, which is not the desired output.

After specifying the metadata for TAGS array as specifieid in the sample above, the output is shown below:

{"title":"Struct Serialization","keywords":["struct","json","serialization","2016","HF2","metadata"],"url":""}

If an array contains values of different datatypes, assign the array of values specifying the metadata of each array element to the key items. For example,

       example = structnew();
       example.firstname = "Yes";
       example.lastname = "Man";
       // define an array for a struct key. Elements are of different datatypes
       example.inputs = ["2500.12", 4.0, "Yes", "False", "339090", {"q1": "Yes"}, ["1","2","3"]];
       // set datatypes of first element as numeric, second element as integer, and so on
       example.setmetadata({firstname: "string", inputs: {items: ["numeric", "integer", "string", "boolean", "string", 
       {q1: "boolean"}, {items: "string"}]}});

The output is:


In the above sample, the inputs array also contains a struct and an array as elements. In such cases, the metadata can be specified on the metadata of inputs array.

Ignoring keys in a struct

You can ignore certain keys in a struct that need not be serialized. Specify the key ignore and set its value to true, as shown below:


For example,

       employee = structnew();
       employee.firstname = "Yes";
       employee.lastname = "Man";
       employee.salary = "100000";
       employee.salarygrade = "D";
       // ignore salary and salarygrade keys
       profileView = {firstname: {type:"string",name:"fname"}, salary: {ignore: true}, salarygrade: {ignore: true}};

The output is:


The salary and salarygrade keys are ignored, while the other keys are serialized, according to the metadata.

Retrieving metadata

You can retrieve metadata using the getMetadata function. In structs, this function provides the metadata information for the struct keys in addition to the type of struct (ordered or unordered). For example, 

    employee = structnew();
    employee.firstname = "Yes";
    employee.lastname = "Man";
    employee.salary = "100000";
    employee.salarygrade = "D";
    profileView = {firstname: {type:"string",name:"fname"}, salary: {ignore: true}, salarygrade: {ignore: true}};

The sample produces the following output:

The returned metadata contains a key called keys that contains the metadata set on the struct. There is a second key ordered that returns if the struct is ordered or unordered

Note: For ordered structs, the value of the key ordered is insertion.

Serializing arrays

Adobe ColdFusion (2016 release) Update 2 introduces setting metadata for an array. You can use the setMetadata function to set the metadata on the array. 

If all the items in the array have the same datatype, you can specify the datatype of the values as a struct with the key items with the value of the datatype in string.

For example, without serialization:

       tags  = ["struct", "json", "serialization", "2016", "HF2", "metadata"];

The sample produces the following output:


Due to lack of datatype information, the string 2016 gets converted into a numeric value. The folllowing sample illustrates metadata set in the array:

       tags  = ["struct", "json", "serialization", "2016", "HF2", "metadata"];
       tags.setmetadata({items: "string"});

The output is shown below:


If the array contains values of different datatypes, specify the datatypes as an array in the metadata. For example,



In the sample below,

       inputs = ["2500.12", 4.0, "Yes", "False", "339090", {"q1": "Yes"}, ["1","2","3"]];
       inputs.setmetadata({items: ["string", "integer", "string", "boolean", "string", {q1: "string"}, {items: "string"}]});


If the array contains a struct or an array, you can specify its respective metadata. If you do not specify the inner array or struct metadata, ColdFusion checks if there is any metadata explicitly defined on the array or struct. If yes, ColdFusion uses the metadata defined explicitly in the array or struct.

Retrieving metadata

Use the getMetadata function to view the metadata information of the array in addition to the array type (synchronized or unsynchronized). For example,

    inputs = ["2500.12", 4.0, "Yes", "False", "339090", {"q1": "Yes"}, ["1","2","3"]];
    inputs.setmetadata({items: ["string", "integer", "string", "boolean", "string", {q1: "string"}, {items: "string"}]});

The sample produces the following output:

The returned metadata contains the metadata set on the array. The items key contains the metadata of th eitems in the array. The type key contains information whether the array is synchronized or unsynchronized.

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy