I am trying to convert a string to json.
var str = "[{Value:0.64,Rate:Hourly,Description:Hourly if more than 50 hours,Upper Limit:null},{Value:1.68,Rate:Hourly,Description:Hourly if less than 400 hours,Upper Limit:500}]"
I tried with stringify and parse but that didn't work.
I tried with below function :
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
Is there a way to use regex or this function to get the expected output with double quotes ("") added to each key value?
I have to as least make the assumption that your KEYS all do not contain a comma. Because, say you have: {a:b,c,d:e} It is ambiguous whether it should be: {a:"b","c,d":"e"} or {a:"b,c",d:"e"}
Just for simplicity, I am also assuming there is no {, }, : characters in your key or value...
The expression is:
JSON.parse(
str
.replace(new RegExp('{','g'),'{"')
.replace(new RegExp('}','g'),'"}')
.replace(new RegExp(':','g'),'":"')
.replace(new RegExp(',([^{][^,]*:)','g'),'","$1')
)
This will be the outcome: