Use regular expressions to eliminate nested quotes within a string

I have a JSON file with numerous double quotes within the values. The file consists of nearly 27,000 records.

I need to eliminate or substitute the double quotes within the values for it to be considered a valid JSON file. How can this be achieved?

The issue I face is that some records contain only one double quote within the value, while others have multiple double quotes nested within them.

Instead of modifying or removing the quotes, another option could be to remove the entire key and its corresponding value as I do not intend to use it. Is there a simpler method to accomplish this?

Below is a snapshot of a single record from the JSON file:

 {
  "adlibJSON": {
    "recordList": {
      "record": [
        {
          "@attributes": {
            "priref": "4372",
            "created": "2011-12-09T23:09:57",
            "modification": "2012-08-11T17:07:51",
            "selected": "False"
          },
          "acquisition.date": [
            "1954"
          ],
          "documentation.title": [
            "A lot of text with numerous extra double quotes like 'this' and 'that'"
          ] ... ...

The complication mainly arises in the value of the key: document.title. I currently use Sublime Text 2 for finding and replacing purposes.

Answer №1

To achieve the desired outcome, it is essential to ensure certain conditions about your data:

  • The key "documentation.title" must be unique in your data.
  • The array linked to "documentation.title" should contain only one element.
  • Avoid having the character "]" within the value.

Follow these steps to proceed:

/* Locate the first occurrence of "[" after "documentation.title" */
n = s.indexOf("[", s.indexOf('"documentation.title"'));

/* Find the index of closing "]" */
n2 = s.indexOf("]", n);

/* Extract the substring between these indices */
x = s.substr(n+1, n2-n-1);

/* Eliminate all double quotes in this string and reconstruct the original value with the necessary correction. */
s.substr(0, n) + '["' + x.replace(/"/g, "") + '"]' + s.substr(n2+1);

Edit: If discarding the corrected value is an option, simply replace it with an empty string.

Answer №2

It seems unlikely that this can be accomplished since it doesn't adhere to regular language rules.

You may encounter similar challenges as those faced when trying to parse HTML with regex.

Your best bet might be to develop your own parser or try to find one already available.

Answer №3

Give this a shot:

json.replace(/(^\s*|:\s*)"/gm, '$1[sentinel]')
    .replace(/"(,?\s*$|:)/gm, '[sentinel]$1')
    .replace(/"/g, '\\"').replace(/\[sentinel\]/g, '"');

Check out the demo here: http://jsfiddle.net/D83FD/

While not foolproof, this method may work for your data set. Give it a try and see how it handles larger data sets.

The idea is to temporarily replace opening and closing quotes with placeholders, escape any remaining quotes, and then revert the placeholders back to quotes.

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

Implementing a feature to close the drawer component from the main page by clicking on the menu button in React-js

Just starting out with reactjs and I've got my main page set up like this: <div > <AppBar position="flex" style={{backgroundColor:'#1A437E'}}> <Toolbar> <IconButton edge="end" color= ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Generate interactive HTML content and showcase JSON data within it

I am working on an AJAX API call that returns JSON format data. My goal is to display each value on the screen using HTML elements. Although I have achieved this, the design is not dynamic as needed. Additionally, I want to show a message ("No data avail ...

js an asynchronous function that runs upon being called

I am facing an issue where I am trying to reference an async function but it ends up executing instead. const Payment = props => { const [buttonAction, setButtonAction] = useState(null); useEffect(() => { if(some true stuff){ ...

Flask encountering an unexpected error while sending an ajax request, despite the fact that a duplicate request from another function is functioning properly

As a novice in Python and Flask, I have found it incredibly helpful to use them for running a webapp on my Raspberry Pi. Initially, I developed the app in HTML with JavaScript handling the logic. Now that I have a "finished" app, I am looking to enhance i ...

When using React's setState function, it sometimes fails to re-render with the most up-to-date data and instead shows

Encountering an issue with my class component where the state is not updating with the current user value on click, but rather displaying the previous value before updating. For example, if the initial value is set to 0 and I try to update it to 20 on clic ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

working with received data from a JavaScript object

Looking for code assistance, I have a data object serving as my data source. var data = [ { "label":"May 7", "value":25736.6, "proID":"ISB" }, // more data objects... ]; I'm manipulating this data to generate another ...

Shifting Directive Logic to a Method within a Vue Component

I am currently working with a VueJS component that utilizes the style attribute in the following way: <section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: [& ...

Tips for enabling JSON access to the content inside a textarea element in HTML:

I'm attempting to develop a button that enables users to save edits to a post they write in a textarea using JSON. However, when attempting to save the data with a PUT request, I encounter the following error: raise JSONDecodeError("Expecting val ...

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

My goal is to manage components asynchronously in Nuxt.js while also showcasing alert messages

My Desired Outcome I am hoping to implement a notification system that notifies the user based on the response from the server. However, since notifications are handled by a separate component, I need to asynchronously call this component in my code. The ...

Guide on extracting the date selected from a Bootstrap datepicker and displaying it in a separate div

I'm currently attempting to extract the date from a button and display it in another div. Initially, I tried using the input tag method but faced some issues. Therefore, I switched to employing the button option with an icon. My main challenge now is ...

Does JSONObject.append create a nested array as the output?

After coming across this particular query, I was able to grasp the solution, but unfortunately, implementing it in my specific case seems challenging. In my current situation, data is fetched through JPA from a mysql database, and I aim to structure this ...

I am looking to initiate the animation by triggering the keyframe upon clicking a button

Is there a way to create an animation triggered by a button click instead of loading the page? Each table data cell has its own class with a unique keyframe defining the style changes over time. @-webkit-keyframes fadeIn { from { opacity:0; ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

Ensure that input fields in Angular/JavaScript always display three decimal places

Currently working with Angular, I am looking for a way to display data to users using an HTML input field of type "number". <input type="number" step="0.001" class="form-control" style="width: 75px" ng-model="product.price" /> My goal is to always ...

Automatically inserting "amp;" into the URL whenever an "&" is present

Is there a way to prevent the browser from adding "amp;" after every "&" in a URL? I'm attempting to retrieve a JSON file from the following URL (). However, it automatically adds "amp;" after each "&", causing the JSON to return null. The URL end ...

The JSON to HTML table conversion in Javascript seems to be malfunctioning

I've been experimenting with some JavaScript code to convert JSON data into an HTML table. After saving the HTML file on my desktop and double-clicking it, I realized that there was no output displayed on the page. Surprisingly, there were no errors s ...