9

i need a valid JSON format to request ES. i have a string like

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

but when i try to use JSON.parse i got error because my string should be like

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

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

thanx

2
  • 2
    why not render a real JSON string out of the data by generating an object first? Commented Jun 15, 2017 at 8:36
  • the problem is that string is generated automatically by kibana ( I recover it through the url) Commented Jun 15, 2017 at 8:46

5 Answers 5

15

maybe you can use :

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

Here is

regex demo


Note

In the group [a-zA-Z0-9-] of characters i use alphabetical digits and a -, maybe you need other so you can use another one

Sign up to request clarification or add additional context in comments.

9 Comments

You're welcome. And @IdrissBenbassou - if this helped you (which it obviously did ;), shouldn't you up-vote (the up-arrow to the left of the answer)? It makes it easier for other having similar problems to find a good answer.
how can i do this in bash ?
Hi @Tanzeel sorry I'm not familiar with bash but you can ask a question and I'm sure you will get an answer in few minutes :)
Works fine, you should add "_" character too to your regex.
Hi @YCF_L , This some how doesn't work if the values have , within them. Any idea on how to handle those?
|
5

This function will add quotes and remove any extra commas at the end of objects

function normalizeJson(str){return str.replace(/"?([\w_\- ]+)"?\s*?:\s*?"?(.*?)"?\s*?([,}\]])/gsi, (str, index, item, end) => '"'+index.replace(/"/gsi, '').trim()+'":"'+item.replace(/"/gsi, '').trim()+'"'+end).replace(/,\s*?([}\]])/gsi, '$1');}

Edit:

This other function supports json arrays.

It also converts single quotes to double quotes, and it keeps quotes off of numbers and booleans.

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

I also tested the regex with the safe-regex npm module

2 Comments

Great answer unfortunately. The first solution is messing up commas in the value for example => {test : "1,000.00"}, the comma in the value is being removed after normalization. And the second solution gets rid of the spaces in the value {test: "2020/11/19 16:11:46" }
Fantastic. You are save my life. Thank you so much
2

Unquoted JSON is not really a valid JSON. It is just JavaScript. If you trust the source of this string:

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

This is NOT recommended for strings from untrusted sources as it could be a security risk.

Given that you are getting the data from Kibana which may be trusted, it should be ok to eval the string.

The other option is to use the regex as probably elaborated by other answers. Alternatively, you may want to fix your Kibana export to give a proper/valid JSON string.

Comments

1

Good day Idriss

if you wanted to place quotes around all the valid key names and values The maybe look at this expression. YCF_L's answer is prefect to what you wanted. But here it is none the less.

{(?=[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, $&");

Comments

0

Node.js Scripting Approach

Here is a node.js script that you can execute that will take in a local file name such as 'config.json' and read the file, replace all the object keys and then write the changes.

// Utility script: Wrap all unquoted parameter names (object keys) with double quotes
// Usage: quote-json-keys.js

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'config.json');

let text = fs.readFileSync(filePath, 'utf8');

// Replace unquoted keys at start of line up to colon with quoted keys.
// It intentionally ignores keys already quoted.
text = text.replace(/^(\s*)(?!\")(\w[\w-]*)(\s*):/gm, '$1"$2"$3:');

fs.writeFileSync(filePath, text, 'utf8');
console.log(
  'Wrapped all unquoted parameter names with double quotes in config.json',
);

Usage:

Update line 7 and change 'config.json' to the name of your local file. Then run node quote-json-keys.js after you saved the above script locally.

const filePath = path.join(__dirname, 'config.json');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.