Skip to main content
Participating Frequently
November 8, 2021
Question

JSON parsing failure: Expected ',' or '}'

  • November 8, 2021
  • 2 replies
  • 900 views

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

    This topic has been closed for replies.

    2 replies

    BKBK
    Community Expert
    Community Expert
    November 11, 2021

    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>
    EddieLotter
    Inspiring
    November 8, 2021

    The 2" and 4" are causing the problem. It's not valid JSON.

    See https://jsononline.net/json-checker 

    DwightAuthor
    Participating Frequently
    November 8, 2021

    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?

    EddieLotter
    Inspiring
    November 8, 2021

    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.