What is the accurate option to choose - jsonlint or JSON.parse?

I was trying to work with a JavaScript string where a key has a value that is the string representation of an array:

{
  "a": "[\"b\",\"c\"]"
}

Interestingly, jsonlint.com states that this is a valid format.

JSON.parse('{"a":"[\"b\",\"c\"]"}');

However, when I try to parse it using JSON.parse(), it throws an error (unexpected token b at position 8). It seems like the issue might have to do with quotes containing escaped quotes - but according to www.json.org, my string should adhere to the standard.

// creating an object with this specific pattern
var o = {};
o['a'] = "[\"b\",\"c\"]";
console.dir(o.a); // -> "[\"b\",\"c\"]"

// examining the JSON string version of this object
var j = JSON.stringify(o);
console.dir(j); // -> {"a":"[\"b\",\"c\"]"}

// attempting to parse a similar string within another variable
var k = '{"a":"[\"b\",\"c\"]"}';
var l = JSON.parse(k); // -> error

So, who is correct in this scenario? Is it jsonlint.com or JSON.parse()?

Answer №1

When creating strings in Javascript, make sure to properly escape special characters like \, or else they may be misinterpreted.

const result = JSON.parse('{"x":"[\\"y\\",\\"z\\"]"}');

console.log(result);

Answer №2

Instead of the traditional methods, I came across some innovative technologies that were completely unfamiliar to me until I searched for them online just now...

const result = JSON.parse(String.raw`{"x":"[\"y\",\"z\"]"}`);

console.log(result);

Answer №3

Make sure to properly escape the backslashes:

var example = '{"a":"[\\"b\\",\\"c\\"]"}';
var data = JSON.parse(example);
console.log(data);

You can also utilize the String.raw tag function (ES6 only):

var example = String.raw`{"a":"[\"b\",\"c\"]"}`;
var data = JSON.parse(example);
console.log(data);

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

Revamping the back button functionality to redirect to a different location

As I face a situation where I need to modify the browsing history dynamically, consider this scenario: I am currently on my page: http://mysite.example.com and then I navigate to another page by clicking a link: http://mysite.example.com/sports Upon clic ...

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

Show the user's username on their profile page by retrieving the name from the database

Upon successful login/signup with various services, I want to display the username on the profile page. However, my database stores user data in different fields depending on the service used - user.twitter.name for Twitter logins, user.google.name for Goo ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

Design a circular progress bar with a cut-off at the bottom

Does anyone have suggestions on how to create a circular progress bar with cropping at the bottom, similar to this example: PROGRESS BAR? I've been searching for a component like this but haven't had any luck. Any ideas, especially utilizing Mate ...

Tips for organizing a series of dates with the JsonConverter attribute

My current project involves working on a WebApi 2 service that returns data in JSON format. Within this service, I make use of two formats for DateTimes: date ("2017-01-31") and datetime ("2017-01-31T12:00:00.000Z"). The datetime format is the primary one ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Looking for assistance in adding some animated flair to your website as users scroll

I don't have much experience in animation but I would like to create some animation effects on scroll down. Can anyone provide suggestions? I attempted using SVG paths, but it didn't work out as expected. What I am aiming for is that when a visi ...

Unable to locate webpack bundle in Express

I'm currently working with Node, Express.js, Webpack, and Handlebars for my app development. Despite searching extensively for a solution, I have not been able to find one that resolves my issue. Below is the structure of my files: Handlebars (main f ...

Creating an instance without assigning a value to a variable in the constructor declaration

I am interested in developing a Node REST API using Typescript and have started by creating a basic class to manage the Express application. import express from 'express'; import { Server } from 'http'; import { injectable } from &apos ...

Encountering a parsing error when utilizing the fill CSS property in React

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"> <g id="flat"> <path d="M43,43H38.952a2.3,2.3,0,0,1-2.273-1.926h0a4.816,4.816,0,0,0-3.642-3.962,4.728,4.728,0,0,0-5.695,3. ...

axios GET and POST requests are not functioning properly, while fetch requests are successful

I recently set up a REST API on Heroku using Express, NodeJS, and MongoDB (mogoose as orm and MongoDB Atlas as well). I am diving into the world of MERN stack development as a beginner ...

The issues of cross-origin domains arise when utilizing iframes with src links originating from the server side

Encountering a cross-origin domain issue, receiving the following error while working with an iframe: candidateInterviewCtrl.js:39 Uncaught SecurityError: Blocked a frame with origin "http://localhost:9000" from accessing a frame with origin "http://local ...

Interacting with touch events in JavaScript on Android devices

I am facing an issue with my HTML page where a div is meant to function as an on-off switch momentarily. The functionality I have implemented looks like this: $('#btn').mousedown(function() { startAction() }) $('#btn ...

Encountering issues with loading a module in Aurelia

I've encountered a peculiar issue while attempting to load a module using Aurelia. The moment library was successfully loaded for date formatting, but when trying to load the numeral library in the same manner with npm install <module> --save, i ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Designing a pair of elements within a single container

I am trying to achieve a layout where Element 1 and Element 2 can grow independently in height. However, I want the container's height to always match that of Element 2, while allowing Element 1 to grow as much as possible without exceeding the height ...

"Revolutionary AJAX-enabled PHP social commenting system with multi-form support

Why is it that when I submit forms using these ajax functions in PHP, they only send to the first form on the page? I have multiple forms under each article and I want them to be submitted separately. What am I doing wrong? ...

How can I pass a JavaScript variable to PHP in order to modify the filename of an uploaded file?

How can I modify the filename for the file upload to include an ID prefix? For example: Let's say I have the ID stored in a JavaScript variable called item_id. Is it possible to add data to data.append and use that in the "upload.php" file? I woul ...