Having trouble escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function.

var myObj = {
        test: "'p'"
    }
    
    var replacer = function (key, value) {
        if (typeof value === 'string')
            return value.replace(/'/g, "\\'");
        else return value;
    };
    
    var JSONstring = JSON.stringify(myObj, replacer, ' ');
    
    alert(JSONstring);
    

https://jsfiddle.net/4fsqozek/1/

However, when I simply do a replace after creating the string without using the replacer function like this:

 var JSONstring = JSON.stringify(myObj).replace(/'/g, "\\'");
    

The regular expression I used works perfectly fine.

EDIT - clarification - when using the replacer function, the output value contains double backslashes like this \\'p\\' , which is not the expected outcome.

Can someone provide an explanation for this?

Answer №1

JSON.stringify encodes special characters

To learn more, visit the following link: How to encode special characters using JSON.stringify

When you include a backslash in a string that will be JSON encoded, the single \ is converted to \\

Upon decoding the JSON content, double backslashes \\ are then decoded into single backslashes \ (which should give you the desired output).

If you keep your existing code and replace the alert(...) with

alert( JSON.parse( JSONData ).result );

you will see

\'p\'

Answer №2

Before stringification, the value undergoes a process with the replacer function which will remove any escape characters. This allows for calling replace() on the JSON string after it has been converted.

For more information, visit this link.

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 JSON, JavaScript, and HTML for dynamic web development

I am a junior computer programmer facing challenges with our JSON project. The objective is to store an object in local storage, but my HTML and JS code are not working as intended. It seems like nothing happens at all. Any suggestions or feedback would ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

Issue with VueJS/Nuxt: When using this.$router.push, the wrong template is being returned to the <nuxt-link> tag

Currently, I'm developing a search feature that takes the value from a select box and sends the user to the appropriate page. However, there seems to be an issue where the wrong template is being called upon rendering, resulting in no content being di ...

Looking for advice on utilizing Node.js and MongoDB to identify platform modifications on a website

I need guidance for a project I'm currently working on. The project involves extracting headers, like the example below in Mongo document format: { "url": "google.com", "statusCode": 301, "headers": { "location": "http://www.goog ...

What is the technique for anchoring elements at the top of the page when scrolling?

There is a common design feature where the sidebar on the left starts at a lower position on the page, but as you scroll it moves up to the top and remains fixed in place instead of disappearing off the screen. This is a popular design trend that I have ...

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...

Dealing with multiple submit buttons in a form with Angular JS: best practices

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form an ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

Tips for refreshing an html table without affecting the scroll location?

HTML: <div class="html_table"></div> # Within the html body tag. Utilizing Ajax function to retrieve table data. var $html_table= $('.html_table'); function ajaxCallFunction() { $.ajax({ type: 'POST', ...

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...

How to access the final element in a JSON document stored in a Blob Storage system

If I need to access the last element of a json file for an Azure blob aggregation test, one option is to download[toStream] the entire file and validate the last element. However, I am curious if there is a more efficient method to achieve this without d ...

difficulty encountered when parsing a JSON file into a list of objects using C#

Struggling with loading a JSON file into my object list. My program is designed to store vehicles like cars, and I want to save this data as a JSON file. When the program is restarted, I aim to load the JSON file so that the stored vehicles appear in the p ...

Troubleshooting IE compatibility for $.trim() jQuery functionality

Having trouble with $.trim() not working in IE but works fine in Firefox. Any ideas why this might be happening? Thanks. $('#GuestEmailAddress').on('blur', function () { var $inputValue = $(this).val(); ...

Restrict the width of an absolutely positioned element to the width of its

FIDDLE I have a situation where I need to position an element absolutely, like a drop-down menu. However, when the window is resized and becomes narrow, there is not enough space for it. My requirements are: - The right edge of the dropdown should not g ...

Implement image uploading feature with Ant Design library in a React JS application

I need assistance with a basic application that allows users to upload images. Once the image is uploaded and the user clicks on the get data from upload button, the result should be displayed in the console as console.log("Received values of form: ", valu ...

Reviewing file information prior to submission

Is there a way or method we can utilize to validate file details (extension and size) before the form is submitted by the user? I have limited knowledge of jQuery or JavaScript, so please provide detailed assistance if that is the solution. I envision tha ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...

Guide to incorporating Ember into an existing HTML file

Planning to integrate Ember 2.0 into an existing HTML page and have a few queries regarding this. Is it necessary to build the ember project beforehand? This results in creating appname.js and vendor.js files. Which js files are essential to be included ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...