简体   繁体   中英

I need to convert this JSON string. Swap single to double quotes and vice versa

I am using JSON.stringify to produce the following JSON string from an object:

"[{\"text\":\"AA\"},{\"text\":\"B'B\"},{\"text\":\"C\\\"C\"}]"

But, the system I need to send this string to requires it to be in this format:

'[{"text":"AA"},{"text":"B\'B"},{"text":"C\\"C"}]'

This is some other kind of JSON (technically not real JSON). I need some kind of replace function that can convert this properly.

This should switch the escaping on the strings

 let str1 = `"[{\\"text\\":\\"AA\\"},{\\"text\\":\\"B'B\\"},{\\"text\\":\\"C\\\\\\"C\\"}]"` let str2 = `'[{"text":"AA"},{"text":"B\\'B"},{"text":"C\\\\"C"}]'` function convertQuotes(str) { // unescape double quotes str = str.replace(`\\"`,'"'); // escape single quotes str = str.replace("'",`\\'`); // replace start and end str = "'"+str.slice(1,str.length-1)+"'"; return str; } console.log(convertQuotes(str1)) console.log(str2); console.log(convertQuotes(str1)==str2); 

These functions seem to solve my problem But is there a better way? I really don't know a great deal about regex syntax.

function jsonConvert(str) {
    var newStr=str.substr(1, str.length-2);
    newStr=replaceAll('\\\\"', 'DOUBLE_QUOTE_PLACEHOLDER', newStr);
    newStr=replaceAll('\\"', '\"', newStr);
    newStr = newStr.replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");
    newStr=replaceAll('DOUBLE_QUOTE_PLACEHOLDER', "\\\"", newStr)
    return "'"+newStr+"'";
}

function replaceAll(find, replace, str){
  return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
}

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