[英]Adding single quotes to values in object (javascript)
I have a string like this : 我有一个像这样的字符串:
"[ {name: foo, type: int}, {name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]"
and i need to add single quotes for values inside every object , to become like this string : 而且我需要为每个对象内的值添加单引号,以使其类似于以下字符串:
"[ {name: 'foo', type: 'int'}, {name: 'status', type:
'string'}, {name: 'boo', type: 'string'}, {name: 'koo',
type: 'data'} ]"
i have tried to use eval
, JSON.parse
, but didn't see the expected result , is there any idea to do this and just add the single quotes for values in objects ? 我曾尝试使用
eval
, JSON.parse
,但没有看到预期的结果,是否有任何想法做到这一点,只是在对象中添加单引号?
This is the whole JSON , but i only need the fields part . 这是整个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} ]"
}
]
}
Here's a way to do it with a regex: 这是使用正则表达式的一种方法:
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'"))
Seems to produce a valid javascript array: 似乎产生有效的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' } ]
Might have to tweak it to suit your use case. 可能必须对其进行调整以适合您的用例。
Here are the tweaks needed to fix Richard's code 这是修复Richard的代码所需的调整
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))
Here is a correct JS object from the "JSON" you posted 这是您发布的“ 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 replacement may be easy for this. 正则表达式替换可能很容易做到这一点。
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'} ]"
Please see below too. 也请参阅以下内容。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.