【问题标题】:Adding single quotes to values in object (javascript)向对象中的值添加单引号(javascript)
【发布时间】:2019-05-24 13:35:50
【问题描述】:

我有一个这样的字符串:

"[ {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,但我只需要字段部分。

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

【问题讨论】:

  • 正确方法?那就是征求意见。但是,没有什么神奇的方法,您必须手动解析字符串才能生成结果。
  • 这个字符串是怎么产生的?
  • 看起来有人不知道如何正确生成 JSON。为什么不能告诉他们?您绝对确定这是返回的内容吗?
  • 服务器正在生成无效的 JSON。修复它,不要尝试修复损坏的 JSON。
  • 您的后端团队正在生成无效的 JSON,是的。字段名称必须用引号引起来。字符串值必须用引号引起来。

标签: javascript json object


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:

这里是修复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" } 
      ]
    }
  ]
}

【讨论】:

  • 谢谢,我会检查这个
  • 我询问了后端团队,他们说data 结果只有res
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多