What could be the reason for the failure of JSON.parse in parsing the following JSON string: `{ "Search results: \":s\"": "" }`?

What could be causing the failure of JSON.parse to parse the JSON string provided below?

Is the JSON syntax incorrect?

Interestingly, even though its custom JSON parser throws the same error as JSON.parse, https://jsonlint.com/ validates this string.

JSON string

{
    "Search results: \":s\"": ""
}

Code

let test = `{
    "Search results: \":s\"": ""
}`
JSON.parse(test);

Result

VM1882:2 Uncaught SyntaxError: Unexpected token s in JSON at position 22 at JSON.parse () at :1:6

Answer №1

To properly handle quotes in JavaScript strings intended for JSON parsing, use double backslashes to escape them:

let test = `{
  "Search results: \\":s\\"": ""
}`
console.log(JSON.parse(test));

{ 'Search results: ":s"': '' }

As mentioned in the comments above, the issue arises when using quotes in JavaScript code strings because the backslash needs to be escaped to retain its functionality as a backslash for future JSON parsing. In JavaScript, the first backslash in a string is treated as an escape character, rather than a literal character as required in this scenario. If the data is sourced from another location besides JavaScript code, a single backslash suffices.

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

Ways to convert various methods of storing JSON text strings

In order to cater for localization in my Unity game to be used in WebGL, I am looking to store all the game dialogues and text in a JSON file. To assist with building the narrative structure of dialogues, I have opted for the Fungus framework within Unity. ...

Event listeners can only be removed within the useEffect hook

I have encountered an issue when trying to remove an event listener added inside the useEffect hook. The listener is set up to run once after the first rerender, thanks to the empty array passed as the second argument in the useEffect call. I attempted t ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

Is it possible to utilize various providers in Next-Auth while still maintaining the same email address?

I am currently developing a Next.js application using NextAuth. At the moment, I have implemented login functionality with Google, credentials, and GitHub. However, I encountered an issue where if a user logs in with Google using the email "[email pro ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

Is your Discord bot failing to log on?

I created a discord bot, but I'm having trouble getting it online. There are no errors and I'm not sure why. Here is my code: const TOKEN = "MyBotsToken"; const fs = require('fs') const Discord = require('discord.js'); const C ...

Determine the type of element existing in the table cell

Currently, I am utilizing protractor to iterate through table cells in an attempt to verify the presence of a checked checkbox. var elements = element.all(by.css(columncssname)); elements.each(function (cell, index) { <--need to confirm if check ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

One way to automatically pass a default date parameter to an AJAX GET call in JavaScript is to set the initial date value before making the request. As the

Upon page load, I want to display the current date's attendance. After selecting a specific date, I aim to fetch and show the details for that selected date. The current issue I am facing: When I search for a particular date, I receive data for bot ...

Use Yii2 to pass an ID when a button is clicked in order to render a partial using

On the index page, I display all the rows and some fields from my model. When a button is clicked, I want a modal to appear with all the data from the corresponding row. When the button is clicked, I need an ajax call to render a partial view. This will i ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

How can I automatically scroll to an anchor element once CSS animation has finished

I am currently working on a CSS animation that looks like this: @-webkit-keyframes flip { 0% {opacity:1;} 100% {opacity: 0;} //This could be 90% //And here could be frame for 100% which would scroll it down. } #headercover { -webkit-animation-name ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

Obtaining a variable from HTML and passing it to Node.js

Currently, I am utilizing express to handle form submissions. Within my HTML file, there are 20 inputs with unique ids such as address1, address2, address3, and so on. In my node js code, I access these input values using req.body.address1. Users have th ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

Looking for Sha1 encryption functionality in jQuery or JavaScript?

I am currently using sha1 encryption coding in PHP <?php echo hash('sha1', 'testing'.'abcdb'); ?> However, I need this encryption to work on a page named xyz.html, causing the current block of code to not function prop ...

Utilizing a drop-down menu to display two distinct sets of data tables

After spending some time on my WordPress site, I've encountered a problem that has me feeling stuck. Currently, I have two functioning datatables which are displaying one on top of the other on the page. Additionally, there is a dropdown selection box ...