将Javascript对象解析为类似JSON的字符串,但使用单引号



这是我的Javascript对象,我将其转换为字符串(JSON(

var myObj = {
name: 'John',
age: 25,
group: 'O+'
}
console.log(JSON.stringify(myObj));

我需要单引号(撇号(('(而不是双引号("(的输出。索引/键上也没有引号或撇号。我希望它看起来像这样:

{name:'John',age:25,group:'O+'}

我试过这个:

var myObj = {
name: 'John',
age: 25,
group: 'O+'
}
console.log(JSON.stringify(myObj).replace(/"([^"]+)":/g, '$1:'));

这将删除索引/键上的引号,但值中仍有引号。需要用撇号替换它们。尝试了更多正则表达式,但它们不起作用。

如果在字符串的末尾再添加一些替换,您实际上可以得到您想要的。这是你的例子:

var myObj = {
name: 'John',
age: 25,
group: 'O+'
}
console.log(JSON.stringify(myObj).replace(/"([^"]+)":/g, '$1:').replace(/\"/g, '"')
.replace(/([{|:|,])(?:[s]*)(")/g, "$1'")
.replace(/(?:[s]*)(?:")([}|,|:])/g, "'$1")
.replace(/([^{|:|,])(?:')([^}|,|:])/g, "$1\'$2"));

你可以在stackexchange上的另一个论坛上找到这个确切的例子。这是链接。

您可以使用JSON.parse reviver来格式化这样的值。

var myObj = {
name: 'John',
age: 25,
group: 'O+',
bool:true,
hello:{
a:'bb'
}
}
const reviver =(key, value)=>{
if(typeof value === 'string'){
return `'${value}'`
}
return value
}
var a = JSON.parse(JSON.stringify(myObj), reviver);
console.log(JSON.stringify(a).replace(/"/g,''));

最新更新