Your Rating: Results: PatheticBadOKGoodOutstanding! 24 rates

Description

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

Returns

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

Category

Conversion functions

Syntax

See also

DeserializeJSON, IsJSON, cfajaxproxy, Using data interchange formats in the Developing ColdFusion Applications, http://www.json.org

History

ColdFusion 11: Added the attribute. useCustomSerializer.

ColdFusion 8: Added function

Parameters

Parameter

Description

var

A ColdFusion data value or variable that represents one.

serializeQueryByColumns

A Boolean value that specifies how to serialize ColdFusion queries.

  • false (the default): Creates an object with two entries: an array of column names and an array of row arrays. This format is required by the HTML format cfgrid tag.
  • true: Creates an object that corresponds to WDDX query format.
    For more information, see the Usage section.
useCustomSerializer

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.

Usage

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:

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:

Element

Description

COLUMNS

An array of the names of the columns.

DATA

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:

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:

Element

Description

ROWCOUNT

The number of rows in the query.

COLUMNS

An array of the names of the columns.

DATA

An Object with the following:

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

The SerializeJSON function with a serializeQueryByColumns parameter value of true converts a ColdFusion query with two columns, City, and State, and two rows of data into following format:

Note

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.

Note

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.

Example

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.

 

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:

 

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

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

 

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

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,

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:

Employee.cfc

 

 

Index.cfm

 

 

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:

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.

 

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.

Labels
  • None
  1. Jul 28, 2014

    Quote from documentation: "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."

    How? Please include an example URL.

  2. Mar 26, 2015

    This is a possible exception: JSON serialization failure: Java object tree too complex to serialize

  3. Jun 17, 2015

    The 'syntax' and 'parameters' sections omit the "secure" argument shown in the 'Additional format for query serialization' section

  4. Jul 30, 2015

    Not all Structs are serialized properly. In the example below I was hoping to see something like TagContext:[{COLUMN:'',ID:'',ETC:''}], instead it is missing.

    Sample Code:  (Tag-Context is missing)

    <cfoutput>

        <cftry>

            <cfset X = undefinedFunction('Apples and Oranges')>

        <cfcatch type="any">

            <cfdump var="#CFCATCH#">

            #SerializeJSON(CFCATCH)#<br>

        </cfcatch>

        </cftry>

    </cfoutput>

     


Searching ColdFusion, English documentation