简体   繁体   English

当字符串在双引号中包含单引号时,如何在 Javascript 中将此字符串转换为 JSON 对象

[英]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-如果 string 只包含单引号,则可以像下面这样解决 -

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.这看起来不像一个有效的字符串化 JSON。

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

error should be wrapped in double quotes instead. error应该用双引号括起来。

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

You can verify it using JSON.stringify您可以使用 JSON.stringify 进行验证

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

Assuming that you're using a valid JSON.假设您使用的是有效的 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.如果您知道唯一的问题是属性名称是单引号而不是 JSON 所需的双引号,您可以使用正则表达式将属性名称上的单引号替换为双引号。

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.这将用双引号替换字符串中具有(单引号)(文本)(单引号)(冒号)格式的任何部分的单引号,这很可能只是属性名称,但请记住,如果您的字符串遵循此确切格式,它也会将单引号替换为双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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