我有一个类似的字符串:
"[ {name: foo, type: int}, {name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]"
我需要为每个对象内的值添加单个引号,以使其像此字符串一样:
"[ {name: 'foo', type: 'int'}, {name: 'status', type:
'string'}, {name: 'boo', type: 'string'}, {name: 'koo',
type: 'data'} ]"
我尝试使用 eval
, JSON.parse
,但没有看到预期的结果,有什么想法要这样做,只添加对象中的值的单引号?
这是整个JSON,但我只需要字段部分。
{
"success": true,
"count": 1,
"data": [
{
"res": "extend: 'someCode', fields: [ {name: foo, type: int},
{name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]"
}
]
}
这是一种使用正则态度的方法:
const val = `[ {name: foo, type: int}, {name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]`
console.log(val.replace(/(w+)s*:s*(w+)/g, "$1: '$2'"))
似乎会产生有效的JavaScript数组:
> eval(val.replace(/(w+)s*:s*(w+)/g, "$1: '$2'"))
[ { name: 'foo', type: 'int' },
{ name: 'status', type: 'string' },
{ name: 'boo', type: 'string' },
{ name: 'koo', type: 'data' } ]
可能必须调整它以适合您的用例。
这是修复理查德代码所需的调整
let val = `[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]`
val = val.replace(/(w+)s*:s*(w+)/g, ""$1": "$2"")
console.log(JSON.parse(val))
这是您发布的" JSON"的正确JS对象
{
"success": "true",
"count": 1,
"data": [{
"res": { "extend": "someCode" },
"fields": [
{"name": "foo", "type": "int"},
{"name": "status", "type": "string"},
{"name": "boo", "type": "string"},
{"name": "koo", "type": "data" }
]
}
]
}
REGEXP更换可能很容易。
var s = "[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]";
console.log(s.replace(/:[ ]*([^ ,}]+)/gi, ": '$1'"));
> "[ {name: 'foo', type: 'int'}, {name: 'status', type: 'string'}, {name: 'boo', type: 'string'}, {name: 'koo', type: 'data'} ]"
也请参见下面。
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/replace/replace