简体   繁体   中英

How Can I convert this complex a string into JSON with "" in key values?

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:

在此处输入图片说明

 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}]" const regStr = str .replace(/:/g,'":"') .replace(/,/g,'","') .replace(/}","{/g,'"},{"') .replace(/^\\[{/,'[{"') .replace(/}]$/, '"}]') jsonResult = JSON.parse(regStr) console.log(jsonResult);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM