What is the reason for JSON.parse throwing errors on the same strings that eval does not?

Imagine having something like this:

var a = '["\t"]'

When you use:

eval('var result = ' + a)

Everything runs smoothly. However, if you try:

var result = JSON.parse(a)

You'll encounter an error: Unexpected token.
The same issue arises with \b and \f: they work with eval but fail with JSON.parse. Why is that? Shouldn't the parser handle "\t" in a consistent manner?

Additionally, both eval and JSON.parse will fail with \n (as expected), but they also both fail with \r. Why does this happen?

There seems to be some confusion here, so could someone explain what's happening? It would be helpful to understand how the parser behaves in these two scenarios.

Answer №1

In order to properly encode the backslash in a JavaScript string, you need to use double backslashes like this:

var b = '["\\t"]'

If you require more information on this topic, I recommend visiting "http://json.org/"

Answer №2

The reason for this error is that the JSON format is not valid.

It's best to avoid manually writing JSON. Instead, utilize the JSON.stringify method to correctly encode your data.

var json = JSON.stringify(["\t"]);
JSON.parse(json);
//=> ["\t"]

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

What is the best way to remove multiple IDs from req.params using Sequelize?

Is there a way to handle req.params that contain multiple IDs? I need to search for and delete these multiple IDs. Here is the code snippet: const ids = req.params; const masterFunders = await masterFunder.findOne({ where: { id: ids ...

Obtain information from an HTTP GET call

I have encountered an issue where I am unable to access the data that is passed with an HTTP GET request from the client to my server. Oddly enough, this setup works perfectly fine for POST requests but not for GET requests. The technologies being used ar ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Triggering a parent component function after a child component function finishes in Vue

When using Vue, I have a main component housing a child component that is loaded onto the page with a button triggering the saveTaskComment() function. Everything works perfectly until it reaches the .finally portion of the child component's function. ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

Is there a specific regular expression that can be used for validating Credit Card Expiry dates in Javascript/Ang

I am currently working on a textfield where users can enter their credit card expiry date in the format mm/yy. To ensure the validity of this input, I have implemented JavaScript validation using regular expressions. Here is an example of what I have tried ...

Send multipart form data to a different server via pipe

I need assistance with handling a POST request on my Node Express server for uploading images through multipart form data. Currently, my Express app is set up to use body parser which does not support multipart bodies and suggests using alternative librari ...

JavaScript Money Exchange

Can currency be recalculated using JavaScript or jQuery? For instance: <div id="price">$99.00</div> Could become <div class="gbp" id="price">£63.85</div> If a class of "GBP" was added to the div tag? ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

Issue with DWR and Android web browser

I recently encountered an issue while trying to access an application through the Android browser. The application uses DWR to maintain connections with connected clients. Everything seems to be working fine, except for the fact that if there is a 2-minut ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

The modal template in Angular UI is not displaying properly with Bootstrap styling

I've been working on displaying a modal template when a row is selected on a table. The issue I'm facing is that upon clicking a row, a 2px thick black shadowed line appears, which seems to represent the modal but doesn't display its conten ...

Loop through an array (obtained from a JSON response) in order to retrieve the values

Currently, I'm working on retrieving the IDs of the steam groups a user is linked to. Below is the JSON data: { "response": { "success": true, "groups": [ { "gid": "111" }, { ...

How to retrieve specific JSON data from a field in MYSQL database

I need to retrieve data from the reviewed_by table where the "company" is "AAA" and the "review" is "Need Review". Here is the structure of the MySQL table : +-----------+ | DATA_TYPE | +-----------+ | text | +-----------+ +-------------------------+ ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Tips for creating a test case for retrieving JSON data from a factory in AngularJS

I'm currently working on creating a test case for a factory that returns a JSON response. However, I've encountered the following error: Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=serviceProvider%20%3C-%20servic ...

Switch up the CSS file based on the URL route

My project consists of the following files: App.vue, changcolor.vue, config.json, main.js, index.html, xyz.css, abc.css. I need a solution where based on the URL, the appropriate CSS file is applied. For instance, if the URL is "xyz.local.com" then xyz.cs ...

Unexpected behavior observed with Async/Await

I am currently learning how to use Async/Await, which is supposed to wait until the Await function finishes executing before moving on with the code. However, I have encountered an issue where my code stops completely after using Await. Here is the method ...