Glossary

What Is ColdFusion JSON Serialization?

Definition

ColdFusion JSON serialization is the process of converting CFML data types—such as structs, arrays, queries, and component instances—into a JSON-formatted string using Adobe ColdFusion’s built-in Features. Put simply, it turns your in-memory ColdFusion data into a text-based JSON representation so you can send it over HTTP, store it, or interoperate with JavaScript and other systems. The primary tools are the functions serializeJSON() and deserializeJSON(), and the automatic serialization that happens in REST and remote CFC methods when you specify a JSON return format.


How It Works

Core Functions

  • serializeJSON(value [, options])

    • Converts a CFML value to a JSON string.
    • Supports complex types (structs, arrays, queries) and simple values (string, number, boolean).
    • Offers flags to influence output, especially for queries and Security prefixes (options vary by ColdFusion version).
  • deserializeJSON(jsonString)

    • Converts a JSON string back into CFML values (structs, arrays, etc.).

Basic example:

  • CFScript:
    • data = {name: “Ada Lovelace”, skills: [“math”,”programming”], active: true};
    • json = serializeJSON(data);
  • Tag-based:
    • <cfset data = {name=”Ada Lovelace”, skills=[“math”,”programming”], active=true}>

The resulting json is a standard JSON string, ready to return in an API response or save to a file.

Automatic Serialization in Remote/REST Methods

ColdFusion can serialize your return value automatically:

  • CFC remote method:
    • public remote any function getUser(required numeric id) returnFormat=”json” { return userStruct; }
  • REST CFC:

In both cases, ColdFusion will automatically call the JSON serializer on the returned value.

What Gets Serialized (and How)

  • Simple values: strings, numbers, booleans become JSON primitives.
  • Structs: become JSON objects with Key-value pairs.
  • Arrays: become JSON arrays.
  • Queries: can be serialized in two common shapes: by-columns or by-rows (details below).
  • Dates/Times: emitted as strings (format depends on version/settings). You can pre-format to control exact output.
  • CFC instances: serialized as JSON objects of accessible properties; functions are ignored. Often you’ll map components to plain structs first for clarity and Security.
See also  What Is CFHTTP and Why It’s Useful?

Data Shapes and Examples

Structs and Arrays

  • Struct to JSON:

    • CFML: { id: 1, name: “Grace Hopper” }
    • JSON: {“id”:1,”name”:”Grace Hopper”}
  • Array to JSON:

    • CFML: [“CFML”,”JSON”,”REST”]
    • JSON: [“CFML”,”JSON”,”REST”]

Query to JSON: By-Columns vs. By-Rows

ColdFusion’s serializeJSON() supports two common shapes for queries. The exact flag names and defaults can vary by version, but conceptually they are:

  1. By-columns (column-centric):
  • Output includes a list of column names and a 2D data array.
  • Useful for compact payloads and some client-side grids.

Example (query with columns id, name, city):

  • {
    “COLUMNS”:[“ID”,”NAME”,”CITY”],
    “DATA”:[
    [1,”Ada Lovelace”,”London”],
    [2,”Alan Turing”,”Manchester”]
    ]
    }
  1. By-rows (row-centric):
  • Output is an array of row objects. Often easier for REST APIs and JavaScript usage.
  • [
    {“ID”:1,”NAME”:”Ada Lovelace”,”CITY”:”London”},
    {“ID”:2,”NAME”:”Alan Turing”,”CITY”:”Manchester”}
    ]

Tip: If your API consumers are JavaScript developers, they usually prefer the by-rows format because it is more intuitive to loop over.

Comparison table:

Aspect By-columns By-rows
Readability Lower Higher
Payload size Often smaller Often larger
Typical API preference Rare Common
Client-side mapping Needs column index lookups Direct property access

Dates and Times

  • JSON has no native date type; ColdFusion serializes date/time as strings.
  • Formatting can differ by CF version and server Configuration. To keep control:
    • Convert dates to a standardized string before serialization (e.g., dateTimeFormat(myDate, “yyyy-mm-dd’T’HH:nn:ss’Z'”) for UTC).
  • Note: Without explicit formatting, timezone and precision details may be ambiguous. For API stability, it’s best to define an ISO 8601-like format explicitly.

Components (CFCs) and ORM Entities

  • ColdFusion attempts to serialize accessible properties of CFCs, but may include internal or unintended fields depending on your design (e.g., accessor methods, persistent properties).
  • Best practice: Map CFCs to plain structs (DTOs) before serialization to control exposure and avoid circular references.
  • For ORM entities, consider manual projection (select only the fields you need) and convert to arrays of structs prior to serialization.

Use Cases

REST/HTTP APIs

  • Expose CFML data (query results, computed structs) as JSON over endpoints.
  • ColdFusion’s REST Features and remote CFC methods simplify returning JSON by automatically serializing the return value.

AJAX in CFML Pages

  • Return JSON to front-end JavaScript for dynamic UI updates without reloading the page.
  • Integrate with frameworks like Vue, React, or plain fetch/XHR.

Microservices and Interop

  • Exchange data with other services written in Java, .NET, Node.js, or Python using JSON as the lingua franca.
  • Serialize domain objects to lightweight JSON DTOs.
See also  What Is a ColdFusion Custom Tag?

Caching and Logging

  • Store JSON snapshots of CFML data in cache layers or log structured events for observability and audits.

Practical Example: A Simple Orders API

Scenario: You need an endpoint that returns orders for a given customer as JSON, row-by-row.

  • CFScript-style service method:
    • component rest=”true” restPath=”/orders” {
      • remote array function listByCustomer(required numeric customerId) httpMethod=”GET” produces=”application/json” {
        • // Query the database
        • q = queryExecute(”
          SELECT orderId, orderDate, totalAmount
          FROM Orders
          WHERE customerId = :cid
          ORDER BY orderDate DESC”,
          { cid: { value: arguments.customerId, cfsqltype: “cf_sql_integer” } }
          );
        • // Convert to array of row structs for readable JSON
        • rows = [];
        • for (r in q) {
          • arrayAppend(rows, {
            orderId: r.orderId,
            orderDate: dateTimeFormat(r.orderDate, “yyyy-mm-dd’T’HH:nn:ss’Z'”),
            totalAmount: r.totalAmount
            });
        • }
        • return rows; // ColdFusion will serialize this to JSON automatically
      • }
    • }

Notes:

  • We return an array of structs, not the raw query, to produce a clean, intuitive JSON shape.
  • Dates are standardized to an ISO-like format.
  • Prepared parameters defend against SQL injection.

Best practices

  • Prefer returning arrays of row structs for queries.
  • Pre-format date/time strings (e.g., ISO 8601) to avoid ambiguity across clients.
  • Control exposure: Convert CFCs and ORM entities to plain structs/DTOs; don’t serialize entire entities with internal state.
  • Set the correct content type: Ensure responses include Content-Type: application/json; ColdFusion REST methods typically handle this automatically.
  • Use UTF-8 consistently and validate your output with a JSON validator if needed.
  • Avoid circular references in nested data; they will break serialization.
  • Minimize payload size: Select only needed columns; paginate; compress at the web server/proxy level when appropriate.
  • Handle nulls explicitly: Decide whether to output null or empty strings and keep it consistent. ColdFusion’s null handling depends on server/application Configuration.
  • Escape only when needed: If you manually build parts of JSON (not recommended), encode values safely. When you use serializeJSON(), escaping is handled for you.

Common pitfalls and Troubleshooting

  • Unexpected query shape: If your JSON returns a COLUMNS/DATA structure but consumers expect an array of row objects, convert the query to an array of structs before serialization.
  • Date formatting surprises: Without explicit formatting, clients may misinterpret dates. Always format.
  • Case sensitivity of keys: Clients may expect property names to be camelCase; rename keys in your DTOs as needed to maintain API Standards.
  • Large payload latency: Serialize only what you need and paginate; serialization of very large nested structures can be slow.
  • Hidden fields in CFC serialization: You might unintentionally expose internal properties. Always define explicit response DTOs.

Key Points

  • JSON serialization in ColdFusion is how CFML data becomes a JSON string for APIs and interoperability.
  • The go-to tools are serializeJSON() and automatic serialization in remote/REST methods.
  • Queries can serialize in two shapes; APIs usually prefer by-rows (array of structs).
  • Explicit date/time formatting leads to stable, predictable APIs.
  • Map complex objects to plain structs to control output, avoid circular references, and improve security.
See also  What Is ColdFusion WebSocket?

Related Syntax Patterns

  • Convert query to array of row structs:

    • rows = [];
    • for (row in q) arrayAppend(rows, duplicate(row));
  • Serialize a prepared DTO:

    • json = serializeJSON(dto);
  • Deserialize a JSON request body:

    • body = toString(getHttpRequestData().content);
    • params = deserializeJSON(body);

Pros and cons of ColdFusion’s Built-in JSON Serialization

Pros:

  • Built-in, no extra libraries required.
  • Works seamlessly with REST and remote CFC methods.
  • Handles common CFML types, including queries.

Cons:

  • Default query shape may not match consumer expectations.
  • Date/time formatting can be inconsistent unless you enforce it.
  • CFC/ORM serialization can expose unwanted fields; manual DTOs often necessary.

Integration Tips for APIs

  • Standardize conventions: camelCase keys, ISO 8601 dates, and consistent null handling.
  • Version your APIs when changing shapes or field names.
  • Add unit/Integration tests that validate exact JSON responses to protect against regressions.
  • Document response schemas for front-end and partner teams.

FAQ

What is the difference between serializeJSON() and returnFormat=”json”?

serializeJSON() explicitly converts a CFML value to a JSON string that you can write or return. returnFormat=”json” (or produces=”application/json” in REST) tells ColdFusion to automatically serialize the returned value for you, including setting the appropriate content type header in many cases.

How should I serialize ColdFusion queries for an API?

Convert the query to an array of row structs for readability and compatibility with common JavaScript usage. While ColdFusion can serialize queries by-columns, most API consumers prefer by-rows because it’s intuitive to iterate over.

How do I control the date/time format in JSON?

Format dates before serialization using functions like dateTimeFormat() to produce a consistent, timezone-aware string (for example, UTC ISO 8601). Relying on default date serialization can lead to inconsistent interpretations by clients.

Can I safely serialize component instances (CFCs) or ORM entities?

Yes, but it’s better to map them to plain structs (DTOs) to avoid exposing internal fields and to prevent circular references. Explicit DTOs give you precise control over what the JSON contains.

Why are nulls missing or turned into empty strings?

ColdFusion’s null handling depends on server and application settings. If you need true nulls in JSON, enable and use null support consistently, and set values to null explicitly where appropriate. Otherwise, decide on a convention (null vs. empty string) and apply it uniformly across your API.

About the author

Aaron Longnion

Aaron Longnion

Hey there! I'm Aaron Longnion — an Internet technologist, web software engineer, and ColdFusion expert with more than 24 years of experience. Over the years, I've had the privilege of working with some of the most exciting and fast-growing companies out there, including lynda.com, HomeAway, landsofamerica.com (CoStar Group), and Adobe.com.

I'm a full-stack developer at heart, but what really drives me is designing and building internet architectures that are highly scalable, cost-effective, and fault-tolerant — solutions built to handle rapid growth and stay ahead of the curve.