Processing JSON data of a quotation that is enclosed within double quotation marks

My value is a string:

"['Eitaj', 'Jason Json', 'Eitaj M', "Jason Json's"]"

Trying to parse it with JSON.parse() results in an error.

Encountered SyntaxError: Unexpected token ' in JSON at position 1

I discovered that the correct working string is:

JSON.parse('["Eitaj", "Jason Json", "Eitaj M", "Jason Json\'s"]')

Are there any alternative tricks I can use besides switching single quotes to double quotes?

Answer №1

Try testing out this solution to see if it meets your needs.

let input = "['Eitaj', 'Jason Json', 'Eitaj M', \"Jason Json's\"]";

let parsedData = JSON.parse(input.split(",").map(segment => {
  return segment.replace(new RegExp("'.*'", "g"), function(match) {
    return '"' + match.substring(1, match.length - 1) + '"';
  })
}).join(","));

console.log(parsedData);

Update 1

Enhanced version of the previous code snippet that addresses some of the issues mentioned in the comments. However, there might still be other specific cases that need to be handled based on your requirements.

let input = "['Eitaj', 'Jason Json', 'Eitaj M', \"Jason Json's\",\"Test'test'Test\",'Acme, Inc.',\"'Test'\"]";

let parsedData = JSON.parse("[" + input.substring(1, input.length - 1).match(new RegExp(`((['\""]).*?(\\2))`, "g")).map(segment => {
  return segment.trim().replace(new RegExp("^'.*'$", "g"), function(match) {
    return '"' + match.substring(1, match.length - 1) + '"';
  })
}).join(",") + "]")

console.log(parsedData);

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 are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

What could be causing the decreasing opacity of lines at the edge of my HTML5 canvas?

I have embarked on the journey of creating a bar graph using an HTML5 canvas. The process involves a series of lines drawn with the help of .moveTo(), .lineTo(), and .stroke(). Below is the code snippet I am using for this purpose. Although I am new to wo ...

Looking to eliminate the "=>" from JSON output in a Ruby on Rails 3 application?

I'm currently facing a small issue that I believe should have a simple solution. I am working on creating JSON data and it needs to have the following format: [{ "source" : "google / organic", "visits" : 20 }] However, this is what I am getting: [{ ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

What is the reason behind unhandled promise rejections?

Whenever I send a post request using Postman to localhost:5000/api/profile/experience, I keep receiving these warnings: UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience ...

Nested JSON objects can be created in PostgreSQL using the json_build_object

Let's start off by noting that I am using PostgreSQL 11.6, which is compiled by Visual C++ build 1800 for 64-bit systems. :) My goal here is to generate a JSON object directly from the database. The outcome I am aiming for is: { "1": [], "2": ...

Unveiling the secrets of interacting with localstorage in react.js

I'm currently facing an issue with a component that retrieves data from an array stored in local storage. Although the initial data is fetched when the page loads, I am unsure how to update it when changes are made in local storage. import React, {Co ...

Tips for monitoring the activities of a different user on a website

I am working on a project where I need to display all the activities of one user to another user on a web page. Essentially, the second user should be able to see everything that the first user is doing on their page. While I know it can be done using AJA ...

Substitute an item with another -JavaScript

While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition ...

Is it possible to send a message from a child iframe to its parent using HTML5 cross-browser compatibility

I've been following this tutorial on a video-sharing website, which demonstrates how to securely pass messages between an iframe and its parent. The tutorial can be found at a specific URL. To achieve this functionality, you would end up with a simila ...

What is the best way to create a scrollable Material UI modal and dialog?

Having a problem with my mui modal where the top content is getting cut off and I can't scroll up. I've tried adding the {overflow:"scroll"} property to the modal but it's not working. Here's the code snippet I'm currentl ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

Restrict User File Uploads in PHP

I have a system set up that enables users to upload files under 200 MB. Once the file is downloaded once, it will be automatically deleted. Additionally, all files are deleted from the server after 24 hours. I am looking for a way to limit the number of up ...

Troubleshooting Error in WebSocket with 'ws' Library in Node.js and Vue.js: Issue with RSV1 Flag Unset

I've come across a problem with WebSocket connections while working on my Node.js and Vue.js project. I've implemented the 'ws' library for WebSocket functionality, but I keep getting the error message "Invalid WebSocket frame: RSV1 mus ...

Nested JSON data within an array using Httpful

For the past 3 days, I've been attempting to use PHP and httpful to display the ID from a test JSON file without success. Despite trying various combinations and even attempting to create a handler to decode the data as an array, I just can't se ...

Currently, my goal is to retrieve large quantities of data from the Europe PMC annotations API using Python

Here is my code snippet: Suppose I have the following code: If name == 'main': json_data=requests.get("https://www.ebi.ac.uk/europepmc/annotations_api/annotationsByArticleIds?articleIds=PMC%3A4771370&section=Abstract&provider=Europ ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...