What could be causing my supposedly correct-looking JSON to be invalid?

I've been trying to figure this out for a while now, but I just can't seem to understand why my JSON keeps showing as invalid...

When I run it through JSONLint, I get the following error

    Error: Parse error on line 107:
...pair?",      "answer": "Yes, as long as the
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

This is the specific part of the JSON that's causing issues

{
    "tags": "already transferred",
    "question": "Can we transfer customers who have already been transferred previously? what is the dispo? warm transfer or already contacted?",
    "answer": "Yes, mark as already contacted."
},

{
    "tags": "secured debt",
    "question": "If customer only has secured debts, can we still offer credit repair?",
    "answer": "Yes, as long as they have at least $100 in secured/unsecured debt.
    "},




    {
        "tags": "state",
        "question": "Is the program state sensitive?",
        "answer": "Yes, each partner has particular states that they service. The script engine will only offer services when the state is valid for partner who has that service."
    },

The issue seems to be with the text 'Yes, as long'

This JSON is generated dynamically using ColdFusion.

<cfscript>faqCounter=1;</cfscript>
    <CFLOOP query="getFAQs">
         <cfoutput>
            {"tags":"#getFAQs.tags#","question":"#getFAQs.question#","answer":"#getFAQs.answer#"}<cfif faqCounter<getFAQCount.getFAQPertinentCount>,</cfif>
         </cfoutput>
        <cfscript>faqCounter++;</cfscript>
    </CFLOOP>

Answer №1

There is a CRLF within the double quotes ""

"response": "Yes, individuals can file for bankruptcy as long as they have a minimum of $100 in secured/unsecured debt.
"},

https://i.sstatic.net/1gkCv.png

Answer №2

( It has been highlighted by previous answers that the issue lies with the un-escaped new line, causing the JSON to break. This emphasizes the importance of avoiding crafting your own JSON and instead utilizing the built-in function SerializeJSON(). )

Lucee 5.2.8.39+

Explore the new support for JSON serialization-related settings in the Application.cfc for Lucee version 5.2.8.39 and above. These new settings allow you to override ColdFusion's default method of serializing query objects:

// serialize queries as an array of structures AND
// preserves the column name case used in the sql
this.serialization.preserveCaseForStructKey = true;
this.serialization.serializeQueryAs = "struct";

This enhancement eliminates the need for painstaking query looping. Simply execute your query and utilize serializeJSON( yourQuery ) to produce a well-formatted string like the example below:

[
  {
    "answer": "Yes, mark as already contacted.",
    "tags": "already transferred",
    "question": "Can we transfer customers who have already been transferred previously? what is the dispo? warm transfer or already contacted?"
  },
  {
    "answer": "Yes, as long as they have at least $100 in secured/unsecured debt.  ",
    "tags": "secured debt",
    "question": "If customer only has secured debts, can we still offer credit repair?"
  }
]

Earlier Lucee versions

If you are using earlier versions of Lucee, follow the suggestion from @Barmar. Construct an array of structures and then employ serializeJSON to convert it into a correctly formatted JSON string.

Runnable Example

<cfset yourArray = []>

   <cfloop query="getFAQs">
      <cfset yourArray.append( { "tags" : getFAQs.tags
                               , "question" : getFAQs.question
                               , "answer": getFAQs.answer
                             } )>    
   </cfloop>

   <cfset jsonString = serializeJSON( yourArray )>

Removing unwanted new lines?

To eliminate unnecessary new lines in your JSON string, apply a replace() function and substitute \n with an empty string.

<cfset jsonString  = replace(jsonString , "\n", "", "all")>

If you wish to remove them permanently, locate the code inserting them into the database initially and modify it there. Additionally, update any existing database entries to eradicate the "\n" characters.

Answer №3

An issue arises when the string includes a newline character as a literal, which should be represented as \n. Most programming languages offer ways to filter or serialize data into JSON format, automatically handling these conversions.

Take a look at the code examples provided in the documentation at

The following script uses the serializeJSON() function to convert data into JSON:

<cfscript>
       example = structnew();
       example.firstname = "Yes";
       example.lastname = "Man";
       // customizing the serialization process by defining the type of "firstname" as string
       metadata = {firstname: {type:"string"}};
       example.setMetadata(metadata);
       writeoutput(SerializeJSON(example));
</cfscript>
{"LASTNAME":"Man","FIRSTNAME":"Yes"}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enlarging an image on canvas and creating a repeating pattern

My canvas size is 500px x 500px. I have a png image that matches the canvas size, which you can view here. I am looking to resize the image to 100px x 100px and then use it as part of a repeat pattern on the canvas. This is how I achieve this: // First d ...

Creating curved triangles in React Native is a fun and easy way to add stylish

Hello everyone, I am a newcomer to react native and I am attempting to create the following user interface. Is there any way to create a curved triangle? I have tried but I am unable to curve the edges of the triangle. https://i.stack.imgur.com/vE17U.png ...

Do I have to include 'document.ready()' for this JavaScript code snippet?

I am currently utilizing freemarker to dynamically generate HTML pages based on user requests. These pages contain a reference to a javascript file in the header section. Within this javascript file, there is an array that is defined. It is necessary for m ...

Displaying files based on time signatures using NodeJS with a delay

I have 6 levels of user tiers. Each tier has a different time delay in viewing posts: 1st tier: See posts immediately upon posting. 2nd tier: See the same post after 60 minutes 3rd tier: See the same post after 120 minutes 4th tier: See the same post af ...

Leverage the power of gRPC with Node.js and TypeScript for seamless

I'm trying to implement GRPC in a Node.js and Typescript project, but I'm facing an issue with generating proto files on Windows 10 using npm. I need to run the file transpile-proto-ts.sh: #!/usr/bin/env bash OUT_DIR="./src" TS_OUT_DIR="./src" ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

What is the best way to implement an input spinner with changing values?

Seeking assistance in creating an input spinner with dynamic values (e.g. 125, 180, 200, 270, 260, etc.) stored in a database using Laravel, JavaScript, HTML, CSS, and Bootstrap. I managed to display the values in a dropdown but struggling to integrate th ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

Accessing the content of a list using a specific parameter in JSON format

I am currently facing some challenges while processing a complex JSON file. Here is a snippet from the XML class that I convert to JSON for easier processing: <Selection Category="M43002NN"> <ReferendumOptionIdentifier>foo</ReferendumO ...

Creating a properly formatted PHP array to be passed to JavaScript

Following code snippet works successfully: $db = $connection->messages; $collection = $db->messagesCollection; $messageArray = $collection->find(array('IDto' => '4')); foreach($messageArray as $messageData){ $messageFro ...

Retrieve the ID of the button that was chosen

Hello, I have a card with 3 selectable buttons as described below. <ul class="nav nav-tabs border-0" role="tablist" id="FlightType" onclick="SelectedFlightType()"> <li cla ...

Is there any benefit to fetching data in `{#await}` or `onMount` instead of `load` in SvelteKit, especially considering the impact on `+server`?

keyword: displaying loading spinner Imagine accessing a route like /dashboard, where most of the page content remains constant but certain sub-components require real-time data. If I retrieve this data within a load function, the entire route will remain ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

Detect if the content loaded in the web view is a PDF file and provide a downloadable option

I am using wkWebView to access research papers from IEEE, Science Direct, and other sources. When I click on a PDF in the research papers, it gets loaded into the webview. Is there a way to detect and enable a download icon in wkWebView? Attempted Solutio ...

What is the proper way to utilize props.theme.breakpoints in conjunction with the makeStyles hooks?

Can anyone help me understand how to incorporate the Material breakpoints provided at https://material-ui.com/customization/breakpoints/ into the makeStyles hook for responsive styling? I am having trouble using props.breakpoints.down('600') with ...

Is there a way to convert an Xml raw string into Xml or Json Output Format?

I am attempting to use FormatFilter in order to generate 'json' or 'xml' output from a controller response. The issue is that my initial xml string is randomly generated. I am working with DotNet Core 2.2 and here is the current code ...

Retrieve precise information from a JSON dataset

Consider the JSON data structure provided below: { "v": "2021", "Outeritems": [ { "items": [ { "c": "r", "KeyOne": "DataOne", ...

I am looking for a way to generate unique dynamic IDs for each input textbox created within a PHP while loop. Can

How can I retrieve the ID of a selected text box generated within a while loop in order to update a field similar to phpMyAdmin? <?php while($row=mysql_fetch_assoc($result)) { ?> <tr> <td><input type ...

Can .NET MVC be used to host vue.js static files?

I recently received a sample Vue app created using vue-cli, which generates static files when the npm run build command is executed. Normally, these files are served by a server from node.js. However, I am curious to know if it's possible to serve th ...