在对象中的值上添加单引号(javascript)

时间:2019-05-24 13:35:50

标签: javascript json object

我有一个像这样的字符串:

"[ {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'} ]"

我尝试使用evalJSON.parse,但没有看到预期的结果,是否有任何想法做,只是在对象中添加单引号?

这是整个JSON,但是我只需要field部分。

{
"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} ]"
    }     
       ]
}

3 个答案:

答案 0 :(得分:0)

这是使用正则表达式的一种方法:

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' } ]

可能必须对其进行调整以适合您的用例。

答案 1 :(得分:0)

以下是修复Richard's code所需的调整

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" } 
      ]
    }
  ]
}

答案 2 :(得分:-1)

正则表达式替换可能很容易。

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