How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this:

{ 
time:  { 
          from:now-60d,
          mode:quick,
          to:now } 
}

However, when I attempt to use JSON.parse, I encounter an error because my string should actually be formatted like this:

 { 
time:  { 
          "from":"now-60d",
          "mode":"quick",
          "to":"now" } 
}

My question is, is there any solution to automatically add double quotes around keys and values of my string?

Thank you.

Answer №1

Consider utilizing the following code snippet:

str.replace(/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)/g, "\"$1\":\"$2\"");

For a demonstration of this regex pattern, visit

this regex demo


Please Note

In the character group [a-zA-Z0-9-], I included alphabetical characters, digits, and a -. If you require different characters, feel free to adjust as needed.

Answer №2

This script is designed to enhance the formatting of JSON by adding quotes and eliminating any unnecessary commas at the end of objects.

function adjustJsonFormat(input){return input.replace(/"?([\w_\- ]+)"?\s*?:\s*?"?(.*?)"?\s*?([,}\]])/gsi, (input, key, value, ending) => '"'+key.replace(/"/gsi, '').trim()+'":"'+value.replace(/"/gsi, '').trim()+'"'+ending).replace(/,\s*?([}\]])/gsi, '$1');}

Note:

A different method has been created that also handles JSON arrays.

In addition, it changes single quotes to double quotes and ensures that numbers and booleans do not have additional quotation marks.

function adjustJsonFormat(input){
    return input.replace(/[\s\n\r\t]/gs, '').replace(/,([}\]])/gs, '$1')
    .replace(/([,{\[]|)(?:("|'|)([\w_\- ]+)\2:|)("|'|)(.*?)\4([,}\]])/gs, (input, start, q1, key, q2, value, end) => {
        value = value.replace(/"/gsi, '').trim();
        if(key){key = '"'+key.replace(/"/gsi, '').trim()+'"';}
        if(!value.match(/^[0-9]+(\.[0-9]+|)$/) && !['true','false'].includes(value)){value = '"'+value+'"';}
        if(key){return start+key+':'+value+end;}
        return start+value+end;
    });
}

The regular expressions used in this function have been validated using the safe-regex npm module

Answer №3

Unquoted JSON may seem like a valid JSON format, but it is actually just JavaScript code. If you are confident in the source of this string:

var obj = eval("'({ 
time:  { 
      from:now-60d,
      mode:quick,
      to:now } 
 })'");

It's important to note that evaluating untrusted strings like this can pose a security risk.

If you are obtaining the data from Kibana and trust its source, then using eval on the string should be acceptable.

Alternatively, you could consider using regex as suggested by other responses, or work on adjusting your Kibana export to provide a properly formatted JSON string.

Answer №4

Hello Idriss

If you are looking to add quotation marks around all valid key names and values, check out this expression. YCF_L's response is exactly what you need. However, here is an alternative solution for your reference.

{(?=[a-z])|[a-z](?=:)|:(?=[a-z])|[a-z](?=,)|,(?=[a-z])|[a-z](?=\})
str.replace(/{(?=[a-z])|[a-z](?=:)|:(?=[a-z])|[a-z](?=,)|,(?=[a-z])|[a-z](?)
=})/igm, $&");

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

Angular, display the chosen option within the text input field

Currently, I have a table with multiple columns and I am using Angular JS to display their values in various controls. For instance, I am using a Select/Option (multiple) to display column A, and I want to use another text box to display column B based on ...

The Navbar is throwing a TypeError because it is unable to retrieve the property 'classList' of null

I am currently experimenting with building a navbar in HTML that has the capability to dynamically switch pages without changing links using href. The method I'm employing to achieve this involves adding a classList of is-active to the div elements wi ...

Issues persist with jQuery ajax request attempting to retrieve data from database

I attempted to retrieve data from my database using jQuery AJAX. Below is the code snippet I used: <script> $(document).ready(function(){ function fetch_data(){ $.ajax({ type:"POST", url:"http://localhost:88/phpPoint/select.php", success:function(re ...

Updating and adding information in a JSON file using PHP functionality

I have a function to control and update data in a post. However, I am encountering an issue where the function both updates existing information and adds duplicate information during the second addition. Can anyone assist me in identifying where the mista ...

Is it possible that the background color won't change on the second click?

Initially, my first click worked fine and successfully changed the background color. However, as soon as I added a second condition, it stopped working. var showBox = $('.show'); showBox.click(function(){ if (parseInt($(this).attr('v ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

Flutter: The parameter type 'Uri' is incompatible with the argument type 'String'

While working on a GIF search feature, I encountered an issue when trying to insert a URL. The error message displayed is "The argument type ‘String’ can’t be assigned to the parameter type ‘Uri’" Below is the code snippet I am using... import ...

What is causing this to function properly on Firefox but not on Chrome or IE?

After clicking the process_2banner button on my html page, a piece of code is executed. Surprisingly, this code performs as expected in Firefox, but not in Chrome or Internet Explorer. In those browsers, although the ajax code is triggered, the div spinner ...

Unable to get angular button hold loop to work properly

My goal is to create a button that can be pressed once to execute a single command, but also has the capability to hold the button down and execute the command multiple times while still holding it. I am working with AngularJs (though I don't believe ...

Ways to periodically create random values and transmit them using MQTT protocol

I need help generating and publishing unique random values to the MQTT protocol every second. Currently, my code keeps sending the same value repeatedly instead of a different one each time. How can I fix this? var mqtt = require('mqtt') var Bro ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Eliminate the registration message from TinyMCE by importing a package

Looking to create a TinyMCE React package, I've been using import { Editor } from '@tinymce/tinymce-react'; However, I'm encountering this message - To remove the message, typically you would add the API key to the .js. in your <scr ...

Leveraging jQuery chosen for interactive form elements

This Table Row contains 5 input fields, with the first being a select box. I am utilizing the chosen jQuery plugin to enable search functionality for the select items. Since this is a dynamic form, I am duplicating these rows. However, I am facing an issu ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Creating a multiline textarea with ellipsis using ReactJS

Looking to create a component with a multiline textfield that displays ellipsis (...) for text overflow beyond 2 lines. How can I achieve this through CSS only without modifying the actual stored text? Utilizing the React component found at: link Appreci ...

When a div tag containing PHP is empty, it should either be hidden or show specific text based on your requirements

Among the plethora of unanswered queries regarding hiding empty divs, I find myself unable to make any of the suggested solutions work. Hence, I am putting forth my own question. On my webpage, there is a specific section dedicated to showcasing various it ...

Associating specific information with individual elements utilizing HTML text box

Seeking guidance on implementing annotations feature for a scatter-plot using d3.js v3. My goal is to show a text-box upon clicking each data point, then display that entered text as a tool-tip specific to that data point. Here's how I'm approach ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...