For the complete experience, please enable JavaScript in your browser. Thank you!

  • Creative Cloud
  • Photoshop
  • Illustrator
  • InDesign
  • Premiere Pro
  • After Effects
  • Lightroom
  • See all
  • See plans for: businesses photographers students
  • Document Cloud
  • Acrobat DC
  • eSign
  • Stock
  • Elements
  • Marketing Cloud
  • Analytics
  • Audience Manager
  • Campaign
  • Experience Manager
  • Media Optimizer
  • Target
  • See all
  • Acrobat Reader DC
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player
  • All products
  • Creative Cloud
  • Individuals
  • Photographers
  • Students and Teachers
  • Business
  • Schools and Universities
  • Marketing Cloud
  • Document Cloud
  • Stock
  • Elements
  • All products
  • Get Support
    Find answers quickly. Contact us if you need to.
    Start now >
  • Learn the apps
    Get started or learn new ways to work.
    Learn now >
  • Ask the community
    Post questions and get answers from experts.
    Start now >
    • About Us
    • Careers At Adobe
    • Investor Relations
    • Privacy  |  Security
    • Corporate Responsibility
    • Customer Showcase
    • Events
    • Contact Us
News
    • 3/22/2016
      Adobe Summit 2016: Are You An Experience Business?
    • 3/22/2016
      Adobe Announces Cross-Device Co-op to Enable People-Based Marketing
    • 3/22/2016
      Adobe and comScore Advance Digital TV and Ad Measurement
    • 3/22/2016
      Adobe Marketing Cloud Redefines TV Experience
CFML Reference / 

SerializeJSON

Adobe Community Help


Applies to

  • ColdFusion

Contact support

 
By clicking Submit, you accept the Adobe Terms of Use.
 

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

SerializeJSON(var [, serializeQueryByColumns, useCustomSerializer])

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:

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:

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:

{"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:

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:

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

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.

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">

<cfscript>
// 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=StructNew();
theWeather.High=73;
theWeather.Low=53;
theWeather.Weather="Partly Cloudy";
weatherArray=ArrayNew(1);
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&" )");
</cfscript>
</cfprocessingdirective>

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:

<cfscript>
data = {empName="James", age="26"};
serializedStr = serializeJSON(data);
writeoutput(serializedStr);
</cfscript>

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

Note: 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
</cfquery>
<cfoutput>#SerializeJSON(qry_Users)#</cfoutput><br>

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

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

Index.cfm

<cfscript>
emp = new Employee({empName="James", age=26, dept="000"});
writeOutput(SerializeJSON(emp));
</cfscript>

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:

[
{"colour":"red","id":1},
{"colour":"green","id":2},
{"colour":"blue","id":3}
]

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.

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

Choose your region United States (Change)   Products   Downloads   Learn & Support   Company
Choose your region Close

Americas

Europe, Middle East and Africa

Asia Pacific

  • Brasil
  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Cyprus - English
  • Česká republika
  • Danmark
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Greece - English
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • Malta - English
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • Southeast Asia (Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam) - English
  • 台灣

Commonwealth of Independent States

  • Includes Armenia, Azerbaijan, Belarus, Georgia, Moldova, Kazakhstan, Kyrgyzstan, Tajikistan, Turkmenistan, Ukraine, Uzbekistan

Copyright © 2016 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

AdChoices