What is the best way to replace a double quotation mark within a string that is already enclosed in double quotation marks using JavaScript

How can I handle a double quote (") within double quotes while using a regular expression in the JSON string provided below?

[{
     "LDAP_ID":"a",
     "LAC_NO":"1153274",
     "ACTION":"VBE",
     "DATE_OF_ACTION":"06-01-2006 AM 12:00:00",
     "RESPONSE":"DPP",
     "DEF_OBSERV":"M",
     "REMARK":"visited b"         s emp & rcd 1 emi",
     "OPR_ID":"FCTV1",
     "ACTION_TO_BE":"",
     "ACTION_TO_BE_DT":"",
     "AMOUNT_TOBECHG":"",
     "DELEGATED_TO":"",
     "BRANCH_CODE":"100",
     "DISP_DATE_OF_ACTION":"06-JAN-06",
     "DISP_ACTION_TO_BE_DT":"",
     "SRNO":"142871",
     "DELETED_FLAG":"",
     "TIMESTAMP":"10-08-2012 AM 11:38:30",
     "STAMPDATETIME":"2012-08-10 11:38:30"
}]

The specific line that requires escaping:

"REMARK":"visited b"         s emp & rcd 1 emi",

Answer №1

Using a standard expression won't suffice to resolve this issue. While you might create one that functions in 99% of instances, it's still inadequate.

Incorrect JSON data must be corrected by a human on the server end. Regular expressions are not designed for tackling these types of dilemmas. It would be more effective to address it at the server level.

Answer №2

If you encounter invalid JSON within JavaScript and need to fix it using regular expressions, the recommended approach is to first receive it as a string, perform the necessary replacements, and then re-evaluate it as JSON. However, it's important to note that this final step can introduce potential risks. A similar question addressing a comparable issue can be found here: Convert object string to JSON

It's advisable to address any issues in the JSON structure before it gets parsed. Nonetheless, if pre-processing is not feasible, you can resort to a solution involving regular expressions.

The provided regular expression specifically targets double quotes within a value by restricting its search between the delimiters of ": and ", ensuring only the intended characters are escaped (modified).

:\s*"[^"]*"[^"]*"\s*(,|\s*\})

Below is the complete code featuring the replacement (with adjustments made to the regex pattern):

var str = '[{ "LDAP_ID":"a", "LAC_NO":"1153274", "ACTION":"VBE", "DATE_OF_ACTION":"06-01-2006 AM 12:00:00", "RESPONSE":"DPP", "DEF_OBSERV":"M", "REMARK":"visited b" s emp & rcd 1 emi", "OPR_ID":"FCTV1", "ACTION_TO_BE":"", "ACTION_TO_BE_DT":"", "AMOUNT_TOBECHG":"", "DELEGATED_TO":"", "BRANCH_CODE":"100", "DISP_DATE_OF_ACTION":"06-JAN-06", "DISP_ACTION_TO_BE_DT":"", "SRNO":"142871", "DELETED_FLAG":"", "TIMESTAMP":"10-08-2012 AM 11:38:30", "STAMPDATETIME":"2012-08-10 11:38:30" }]'

var j = str.replace(/(:\s*"[^"]*)"([^"]*"\s*(,|\s*\}))/g, '$1\\"$2');

var json = JSON.stringify(eval("(" + j + ")"));

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 assign the value of a slide range to a PHP variable?

How can I assign the value of a slide range to a PHP variable? I am looking to store the value of a slide range in the variable $amount Click here for an example $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 0 ...

What is the best way to include content within the li element?

I'm trying to figure out how to insert a block inside an li element in HTML. Here's what I have: <ul> <li> <button onclick="expand()">+</button> Parent 1 </li> </ul> This is what I want ...

width of the cells within the grid table

What is the best way to ensure the width alignment of cells in both the header and main section? I have highlighted the correct option in the image with green checkmarks. Check out the image here. Here is my example and solution: View the code on CodePen. ...

The appearance of an escape character has been detected within the JSON output

Currently, I am facing an issue while writing to an Avro file that is being sent to Snowflake. One of the fields in this process contains a blob of JSON data. The JSON structure consists of various elements and values, and its format is dynamic and unknow ...

Is it possible to output the value of history.go(-1) using a print function?

Currently, I'm working on enhancing a Vue application. My goal is to retrieve the value of the previously visited page using history.go(-1) and then use that value to assign certain values to a variable. This is what I have in mind: <script> ...

Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure: --Events ----Races -------Participants Below is some dummy data example that represents the type of data I need to store in Firebase: var dummyData = [ { ...

Transforming a protobuf Dynamic Message from a gRPC request into JSON format or an equivalent object

When making a gRPC call to a server using reflection, I receive a Dynamic Message as the response message. Despite its appearance resembling a nested object, it has a structure that differs slightly from JSON. This presents challenges when trying to fetch ...

Response from jQuery AJAX yields an object

Here is the AJAX request I am working with: $(function(){ $("#MPrzezn").typeahead({ hint: true, highlight: true, minLength: 3 }, { name: 'test', displayKey: 'value', ...

The Ionic framework lacks support for the firebase and auth properties found in Firebase

Currently, I am developing a user-generated content feature along with buttons using ionic 5 and integrating it with the firebase app. I have been studying posts to incorporate them into my application. I am utilizing: "firebase": "^8.1.1&q ...

Utilizing $dataprovider in Yii2 to efficiently return JSON Data

I'm trying to figure out how to return the $dataProvider in JSON format in Yii2. Here is the code I have: public function actionIndex() { $searchModel = new DraftSearch(); $dataProvider = $searchModel->search(Yii::$app->request->quer ...

Sorting and filtering data using AngularJS filter and orderBy inside a controller or factory

I am currently working with a factory that looks like this: app.factory("ModuleFactory", function (api, $http, $q, filterFilter) { var moduleList = []; var categoryList = []; var moduleTypeList = []; var academyModuleTypeList = []; var mostUsed = []; var ...

Using CSS to create a zoom effect with absolute positioning

I am attempting to implement an interesting effect on my website where clicking a thumbnail causes a full-size div to "zoom in" from the thumbnail. My initial strategy involved using CSS and jQuery, setting the full-size div to position:absolute with top a ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

How to handle duplicate keys in JSON parsing using Python3

Excuse my lack of experience in this area, but there's a json response that looks like this; import json jsonObj = json.loads(""" { "data": [ { "name_space": "name", "value": &q ...

Ruby - TypeError: Hash cannot be implicitly converted into a String

Why is the text variable empty when trying to parse JSON? Desired result: text should contain the following string: Hello world\n\nApple, Harbor\n\nBanana, Kitchen\n\nMango, Bedroom text = "Hello world" json = '{"fru ...

Leveraging Express request-specific variables to facilitate logging with correlation IDs

Our node express app is now incorporating correlation id's to link requests together. These id's are sent in the header from other services, and our middleware captures them, creates a bunyan logger with the id, and includes it in the request obj ...

Building a Dynamic Dropdown Menu in AngularJS with JSON Data

My JSON data looks like this var data = [{ "DocList": [ { "Events": [ { "CategoryName": "PressStatements", "DisplayName": "Press Statements", "ID": 9 }, { "CategoryName": "Report ...

Struggling to remove a row from the MUI DataGrid within a MERN CRUD application with Redux/RTK?

Struggling to understand why the delete button isn't working on my Material UI (MUI V5) Data Grid table. As a beginner in coding, especially with MERN and Redux, my mind is overwhelmed after trying various solutions all weekend - Google, Stack Overflo ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...