Modify JSON from using single quotes to double quotes using JavaScript

Received a JSON from the backend to the front end that uses single quotes throughout, causing issues with a Magento 2 widget. The JSON structure is as follows:

{ 'mood': 'happy', 'reason': 'why shouldn't I?'}

The task at hand is to convert all single quotes to double quotes without altering the apostrophes within. Using a regular expression seems to be the most efficient approach by targeting JSON-related single quotes for replacement.

Despite various attempts and solutions found on SO, none have been successful in the past hour and a half. The closest solution attempted was:

goodJson = brokenJson.replace(/(?<=[{,:] )'|'(?=[:,]| })/g, '"');

This regex pattern aims to replace single quotes preceded or followed by specific characters, but it falls short when the last quote next to a closing curly brace remains unaffected in the output.

If you can shed some light on why this method fails and suggest an improved approach to achieve the desired result, it would be greatly appreciated.

Answer №1

While the character string you provided may not adhere to a JSON format, your attempt with regex was very close to producing the correct outcome:

const fixJson = incorrectJson => incorrectJson.replace(/(?<=[{,: ])'|'(?=[:, }])/g, '"');

console.log(fixJson("{ 'mood': 'happy', 'reason': 'why'd not' }")); // { "mood": "happy", "reason": "why'd not" }
console.log(fixJson("{'mood': 'happy', 'reason': 'why'd not'}")); // {"mood": "happy", "reason": "why'd not"}

Best of luck!

Answer №2

It has been noted by others that this data is not in the correct JSON format, and it would be best to address this issue at the source. If you need to convert improperly formatted JSON to a more flexible version where all values are treated as strings, you can utilize the following function:

function fixBrokenJson(str) {
 return str.replace(/'(\w+)' *: *'(.*?)'(?=[,| *\}])/g, '"$1": "$2"');
}

[
  "{ 'name': 'John', 'age': '30'}",
  "{ 'name': 'Jane 'Doe'', 'age': '25'}",
  "{ 'name': 'Alice', 'age': '28',}",
].forEach(str => {
  console.log('original: ' + str + '\n fixed: ' + fixBrokenJson(str));
})

Output:

original: { 'name': 'John', 'age': '30'}
 fixed: { "name": "John", "age": "30"}
original: { 'name': 'Jane 'Doe'', 'age': '25'}
 fixed: { "name": "Jane 'Doe'", "age": "25"}
original: { 'name': 'Alice', 'age': '28',}
 fixed: { "name": "Alice", "age": "28",}

From the output above, it is evident that the third string is still problematic. Adding additional conditions can help mitigate this issue, but may introduce new challenges.

Understanding of the regex used:

  • '(\w+)' -- expects key with single quotes around it
  • *: * -- expects colon with optional spaces before and after
  • '(.*?)' -- expects value with single quotes around it, non-greedy approach
  • (?=[,| *\}]) -- positive lookahead for a comma or end of object

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

Combining two JSON responses using AngularJS

$scope.addUserJson = $scope.adduser; console.log($scope.addUserJson); Output Object {"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563b3f3d16313b373f3a78353 ...

The grid expands to cover the entire width of the browser

Hello everyone, I am a newbie when it comes to JavaScript and CSS. I am in need of a code, whether it be JavaScript or CSS, that will allow me to stretch out a grid layout measuring 5 x 2 along with pictures to completely cover the width of the browser wi ...

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Refreshing a div's content with a single click to update the page

I'm experimenting with elements above my head and striving to absorb new knowledge. In my admin page, I use jQuery to reveal a hidden div that displays another page within it. Here's how I achieve this: $(document).ready(function(){ $("a#fad ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

When I try to move my object, it seems to have a mind of its own and flies off the canvas instead of staying where

I am in the process of developing a simple game for a class project. Currently, I am working on ensuring that my rectangle stays within the boundaries of the canvas as I move it using a bounce function. However, I am facing difficulties as the rectangle ...

Changing the size of an iframe and closing it by pressing the ESC

I am developing an application that requires the ability to resize an iframe. When the user clicks the "Full Screen" button, the iframe should expand to occupy the entire screen. The iframe should return to its original size when the user presses the "Es ...

Identify all div elements with a specific class within the parent div

How can I use query selector to exclusively target the p and p2 divs inside of a r class, without selecting them if they are outside of that class? <div> <div class="r"><div class="p"></div><div class="p2"></div></di ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Building a custom React carousel using visibility logic starting from the ground up

Can anyone explain the logic or algorithm behind a Carousel? I have been researching how to display one item at a time, but in my case, I need to display three items. When I click on next, I want the first item to hide and the fourth item to appear. <di ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Whenever I add a new Task in React.js, the date is not visible to me

I'm currently deepening my understanding of React, and I've encountered a roadblock. The issue arises when I attempt to create a Tracking Task - the task is successfully created from the form inputs but the date associated with the new task isn&a ...

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Refreshingly modernizing SVG in Angular

I've been facing a challenge in my Angular application where I am trying to dynamically add paths to an SVG element within an HTML file. The issue is that even though the paths are getting added to the DOM, they are not showing up in the browser when ...

Is it possible to create cloud functions for Firebase using both JavaScript and TypeScript?

For my Firebase project, I have successfully deployed around 4 or 5 functions using JavaScript. However, I now wish to incorporate async-await into 2 of these functions. As such, I am considering converting these specific functions to TypeScript. My conc ...

Django views are not receiving multiselect data from Ajax requests

As a newcomer to Django, I am still learning the ropes. One challenge I am facing involves a multiselect list on my webpage. I need to send the selected items to my views for processing, and I attempted to accomplish this using Ajax. However, it seems that ...

Include CakePHP named parameters in the URL when selecting from a list

If I have a selection list like the one below: <select name='languages'> <option value='german'>German</option> <option value='english'>English</option> </select> How can I use Jav ...