Copy link to clipboard
Copied
I am getting a JSON parsing error (JSON parsing failure: Expected ',' or '}' ) when I try to serialize content returned from an external web service. The content has a double quote in it so CF does not view it as valid JSON. I know you can add a character to escape it, but I do not control the web service so how can I escape the character or format the json content so I can serialize it?
<cfhttp method="get" url="MyAPIURL" result="GetJSONResult">
<cfhttpparam type="Header" Name="Ocp-Apim-Subscription-Key" value="MyKey">
</cfhttp>
<cfset JSONResult = deserializeJson(GetJSONResult.filecontent)>
<cfdump var="#JSONResult #">
Here is how the JSON is formatted.
[
{
"id": "1234",
"description": "Stud 2" x 4" x 8ft long "
}
]
Copy link to clipboard
Copied
The 2" and 4" are causing the problem. It's not valid JSON.
Copy link to clipboard
Copied
Thank you for your response! yes I realize that the double quotes are causing the issue and that I can escape them with 2\" x 4\". What I don't know is how I can escape it progomatically from the external API I am calling? Or does the API need to be updated to escape the characters?
Copy link to clipboard
Copied
It's not something you can easily fix on your side without writing your own sophisticated JSON parser that looks for invalid items and attempts to correct them.
The external API vendor needs to fix their API to ensure it emits valid JSON for you to consume.
Copy link to clipboard
Copied
Search the web for a Java library (JAR) that can escape special JSON characters. Place the JAR in ColdFusion's lib directory.
Your code will then be something like:
<cfhttp method="get" url="MyAPIURL" result="GetJSONResult">
<cfhttpparam type="Header" Name="Ocp-Apim-Subscription-Key" value="MyKey">
</cfhttp>
<!--- The tool you have imported --->
<cfset JSONTool = createobject("java","class.name.of.json.tool")>
<!--- Assuming that 'escapeJSON' is a function of the tool --->
<cfset JSONResult = JSONTool.escapeJSON(GetJSONResult.filecontent)>
<cfif isJson(JSONResult)>
<cfset Result = deserializeJson(JSONResult)>
<cfdump var="#Result#">
<cfelse>
Oops. The result isn't JSON: <br>
<cfoutput>#JSONResult#</cfoutput>
</cfif>