在将字符串转换为对象时获取syntaxError意外标记非法

时间:2017-08-12 12:54:29

标签: javascript arrays node.js type-conversion

我正在尝试在对象数组中转换提供的字符串

var string = "[{cpu:100,memory:47,freeDisk:83,networks:[{name: \"ctm-4680b9b244c\", status : \"active\"},{name: \"ctm-c2f21106323\", status : \"active\"},{name: \"ctz-1977174d443\", status : \"active\"},{name: \"ctz-1b49d8ccfa5\", status : \"active\"},{name: \"ctz-28c7ceda9ce\", status : \"active\"},{name: \"ctz-3337b7f252a\", status : \"active\"},{name: \"ctz-bbe9792d0c7\", status : \"active\"},{name: \"ctz-d400e32307d\", status : \"active\"},{name: \"ens33\", status : \"active\"},{name: \"lo\", status : \"active\"},{name: \"ctz-9bf91c248f9\", status : \"inactive\"}],infrastructurename:\"ct-colormaster-host\", infrastructurestatus:\"running\", infrastructureuptime: \"Sat Aug 12 00:00:00 UTC 2017\", infrastructureuptimeSince:{ days: 0, hours: 3, minutes: 39},infrastructuredowntime:', infrastructuredowntimeSince:{days: 0, hours: 0, minutes: 0}, infrastructurecurrentCheckTime : \"Sat Aug 12 06:23:25 UTC 2017\"}]"

我需要将其转换为

[
  { 
    cpu:100,
    memory: 47,
    freeDisk: 83,
    networks: [
      {
        name: "ctm-4680b9b244c",
        status: "active"
      },
      {
        name: "ctm-c2f21106323",
        status: "active"
      },
      ... 
    ]
  }
]

我尝试JSON.parseeval,但他们都没有工作,并给我意外令牌非法错误

请建议我如何将此字符串转换为对象。

1 个答案:

答案 0 :(得分:0)

如果首先必须是字符串,则需要在属性名称周围加引号:

[{ "cpu" : 100 }]

此外,我不确定您是仅为问题创建内联字符串,还是在实际代码中执行此操作。如果它在您的实际代码中,您可以使用单引号来避免转义双引号:

var string = '[{"name": "ctm-4680b9b244c"}]'