Skip to main content
Participating Frequently
Nov 8, 2021 12:41 AM UTC
Question

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

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 is closed to new replies. Start a new post to keep the conversation going.

    4 replies

    BKBK
    Community Expert
    Community Expert
    Nov 11, 2021 10:31 AM UTC

    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>
    Translate
    EddieLotter
    Inspiring
    Nov 8, 2021 3:41 PM UTC

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

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

    Translate
    DwightAuthor
    Participating Frequently
    Nov 8, 2021 3:50 PM UTC

    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?

    Translate
    EddieLotter
    Inspiring
    Nov 8, 2021 3:55 PM UTC

    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.

    Translate