简体   繁体   中英

How to convert this String to JSON object in Javascript, when the string has single quote within the double quote

If the string contains only double quotes, it can be solved like below-

var str=`{"name":"javascript"}`;
var jsonObj=JSON.parse(str) //Works

And if string contains only single quotes , it can be solved like below-

var str = "{'result': ['def', 'abc', 'xyz']}";
str = str.replace(/'/g, '"');
var res = JSON.parse(str);
console.log(res.result);

But how do we convert the below string, where there's single quote inside the double quote-

var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} ` 

This doesn't look like a valid stringified JSON.

var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} ` 

error should be wrapped in double quotes instead.

var s=`{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"} ` 

You can verify it using JSON.stringify

JSON.stringify({
  error: "No such file or directory: '../FileSystem/3434-5433-124/'"
})

Assuming that you're using a valid JSON. You can now escape the single quotes with a backslash.

 var s = `{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"}` const parsed = JSON.parse(s.replace(/\\'/g, "\\'")); console.log(parsed)

If you know that the only issue is that the property names are single quoted rather than the JSON required double quotes you could use regex to replace the single quotes on property names with doubles.

var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} ` 
const regex = /(')(\S*)('):/g
s = s.replace(regex, '"$2":')
const workingJson = JSON.parse(s);

Should do the trick. This will replace single quotes with doubles for any part of your string that has the format of (single quote)(text)(single quote)(colon), this will most likely only be property names but keep in mind that if another part of your string follows this exact format it will also get it's single quotes replaced by doubles.

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