Error in Fetch Response: Invalid escape character encountered in JSON data

I'm currently facing an issue with a fetch request that communicates with an API and receives a JSON object in return. The problem arises when the API includes escape characters for single quotes, such as isn\'t. This causes an error during the JSON parsing process, leading me to seek a way to manipulate the response body before calling response.json(). Below is the snippet of my existing code:

    httpCallout(){
    fetch('/1.0/?method=getQuote&lang=en&format=json', {method: "GET", cache: "no-cache"})
    .then(response => {
      return response.json()
    })
    .then((data) => {
      const quote = data.quoteText;
      this.setState({
        quote: quote,
        author: data.quoteAuthor
      });
    });
    this.colorChange(rgb);
  }

The main issue occurs specifically when response.json encounters an escaped single quote. While I could simply catch the error and move on, I am determined to find a solution that allows me to remove the escaped single quote and still update my state accordingly.

In essence, my goal is to alter a response containing a quoteText value like

"It\'s tiring isn\'t it?"
to be properly parsed as
"It's tiring isn't it?"
before executing response.json() to prevent any Bad escape character errors.

Answer №1

If you're struggling to convince the data provider to tidy up their database or JSON encoding process, there is still a way to clean up the text manually:

Combining these steps in your function will look something like this:

function httpCallout () {
  fetch('/1.0/?method=getQuote&lang=en&format=json', { method: 'GET', cache: 'no-cache' })
    .then(response => response.text())
    .then(text => {
      const cleanText = text.replaceAll("\\'", "'");
      return JSON.parse(cleanText);
    })
    .then(data => {
      const quote = data.quoteText;
      this.setState({
        quote: quote,
        author: data.quoteAuthor
      });
    });
  this.colorChange(rgb);
}

When specifying the arguments for String.replaceAll(), remember to double escape the initial backslash but leave the single quote untouched, resulting in:

text.replaceAll("\\'", "'")

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

The unique capabilities of services and factories in Angular 1 - understanding their differences and what each excels at

After extensively combing through numerous stackoverflow posts and articles, the consensus seems to be that an angular service returns an instance, while an angular factory returns any desired object. This raises the question: what unique capabilities do ...

What is the best way to execute a JavaScript function when the onSelect event of a jQuery datepicker is

Is there anyone who can assist me? I am currently working with a JavaScript function: function updateAb(param){ some manipulation } I also have a datepicker jQuery plugin that I am using for the onSelect event, like so: $( ".datepicker").datepicker({onS ...

Altering CSS attribute values using a random number generator

Is there a way to randomly change the animation-duration attribute in the following CSS code? I want it to range from 0 to 1. @keyframes blink { 50% { border-color: #ff0000; } } p{ animation-name: blink ; animation-duration: 0.1s ; animatio ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

Tips for organizing data from a JSON response and displaying it in a predetermined order within a table

I'm seeking assistance with parsing a response from the API and updating the table section and row based on the order preference of the key "deck". Currently, I am creating a Dictionary by grouping similar types of "deck", but after grouping, the seq ...

What could be the reason for encountering the error 'google not defined' and 'TypeError: Cannot read property 'PlacesService' of undefined at initialize' in this snippet of code?

I'm currently working on implementing a Google Maps API to display markers for nearby restaurants and cafes. However, I keep encountering the following two errors: Uncaught ReferenceError: google is not defined at index.html:47 Uncaught (in prom ...

Having difficulty selecting a choice from a dropdown menu

I am hoping to generate a spreadsheet with details on items for my friend and me, such as selling price, cost, and status (Sold, in the sale, etc). I am aiming to automate the "status" column by incorporating dropdown menus with options like "Sold!", "wait ...

Tips for updating comments using ajax technology

I need to implement AJAX in order to update the page automatically whenever a new comment is added, eliminating the need to manually refresh the page. I have attempted to achieve this by adding a section of code but it's not working as expected. Even ...

Working with nested arrays in Mongoose/Javascript: Adding an Object to an Array within another Array

I have been attempting to add an object to an array that is nested inside another Array in Mongoose. Essentially, it's like having comments for the comments. Below is the structure of my schema: const Schema = new mongoose.Schema ({ name: {type: Str ...

How can you personalize the dropdown button in dx-toolbar using DevExtreme?

Currently, I am working with the DevExtreme(v20.1.4) toolbar component within Angular(v8.2.14). However, when implementing a dx-toolbar and specifying locateInMenu="always" for the toolbar items, a dropdown button featuring the dx-icon-overflow i ...

Instructions on selectively sorting an array within a MongoDB collection document

Seeking guidance as a newcomer to MongoDB. I am attempting to create a collection in my database with a single document that contains a key `cities`, which is an array comprising of 124247 objects. Below is the code snippet for reference: const express = ...

How can JSON be used to hide the label of an empty UITableViewCell?

Hey there, I'm working on a custom TableView where I need to hide empty UILabels within UITableViewCells. I'm trying to populate the cells with values from a JSON webservice. Here is a snippet of what my JSON values look like: ( { p ...

The error message "Uncaught TypeError: Cannot read property 'getUniforms' of undefined" is thrown from the ThreeJS r82 Custom Shader in the three.min.js file at line

I've been working on setting up a js fiddle to showcase an issue I'm currently tackling with a custom shader. After linking it to three.min.js for r82, I encountered some runtime errors during rendering. Interestingly, this problem was absent whe ...

Is there a way to manage a JSON file independently of my GitHub repository, like hosting and editing it separately?

I'm currently developing a Discord bot and am exploring options to host it using Heroku and GitHub. My plan is to store user data in a JSON file, but I'm facing challenges when trying to edit the file directly in the repository. I'm seeking ...

Challenges associated with implementing HTTP in Ionic version 3

I've been working on developing an app using Ionic 3 and I decided to implement the HTTP module. For reference, I relied on the official documentation provided by the Ionic framework. Documentation Link: https://ionicframework.com/docs/native/http/ ...

Having trouble with submitting a Vue.js form when toggling the visibility of a bootstrap panel?

There are three bootstrap panels that are displayed depending on the selection made in the select element: <div class="panel panel-default"> <Select/> </div> <div class="panel panel-default" v-if="fileMode == 0"></div> <d ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

What is the best starting dataset to use from a large pool of data points when creating a stock line chart in High

I am working on creating a line stock highchart similar to the example shown here: https://www.highcharts.com/demo/stock/lazy-loading In the provided example, the initial load fetches data from https://demo-live-data.highcharts.com/aapl-historical.json, s ...

Guide to importing a JavaScript file into a different JavaScript file

I encountered an issue while trying to import a JavaScript file into my server-side JavaScript file. The function I need to run cannot be executed on the server side. Is there a method to successfully import my source code to the server-side JavaScript fil ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...