Cfcontent() returns unparseable JSON

I have a very simple script that creates a struct, turns it into JSON using serializeJSON() and returns the result using cfcontent. The problem is that when I use cfcontent() the resulting JSON is unparseable. Here is my code:

<cfset validation_result = structNew()>
<cfset validation_result["isValid"] = true>
<cfset validation_result["messages"] = "All values are valid">

<cfset validation_result_json = trim(serializeJSON(validation_result))>

<cfdump var="#variables#">

This results in:

Screen Shot 2024-11-11 at 2.59.04 PM

Looking good so far. But when I do this:

<cfset validation_result = structNew()>
<cfset validation_result["isValid"] = true>
<cfset validation_result["messages"] = "All values are valid">

<cfset validation_result_json = trim(serializeJSON(validation_result))>

<cfcontent type="application/json" variable="validation_result_json">

The result is this:

Screen Shot 2024-11-11 at 3.05.06 PM

However, if I take a slightly different approach, I can get it to work:

<cfset validation_result = structNew()>
<cfset validation_result["isValid"] = true>
<cfset validation_result["messages"] = "All values are valid">

<cfset validation_result_json = trim(serializeJSON(validation_result))>

<cfheader name="content-type" value="application/json">

<cfoutput>#validation_result_json#</cfoutput>

Screen Shot 2024-11-11 at 3.07.29 PM

So what’s going wrong with cfcontent? I was suspecting some sort of whitespace character was causing an issue, but if I look at the raw response data from the last example this is what I see:

Screen Shot 2024-11-11 at 3.09.13 PM

Obviously whitespace isn’t the issue, at least not as far as the browser is concerned, but I’d rather use cfcontent if I can so I don’t need to worry about the whitespace at all. I was able to replicate this using TryCF so maybe I’m not understanding something about how cfcontent works? Can anyone tell me what’s going on here?

OS: Windows Server 2022 (10.0) 64bit
Java Version: 11.0.23 (Eclipse Adoptium) 64bit
Tomcat Version: Apache Tomcat/9.0.89
Lucee Version: Lucee 6.1.0.243

I think the ‘variable’ attribute in cfcontent is expecting a binary value, typically used to send a file to the client.

Like martin already said, variable expects a binary.
If you want to use cfcontent to direct send json-data you have to do it like this:

<cfcontent variable="#toBinary(tobase64(serializeJSON(validation_result)))#" type="application/json" />
1 Like

Incredible, thank you. I knew I had to be overlooking something obvious.

I can’t see any binary value in your struct that has to be outputted. Besides JSON is always a string (even if you use application/json). Have you also tried to use the reset attribute and set it to true within the cfcontent-tag and stop it immediately after with an abort? I’ve seen cfml breaking JSONs in application/json because of generated whitespace lots of times.