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