【发布时间】:2018-01-20 21:00:14
【问题描述】:
我正在尝试将提供的字符串转换为对象数组
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.parse 和eval,但它们都不起作用并给我意外的令牌非法错误。
请建议我如何将此字符串转换为对象。
【问题讨论】:
-
为什么它首先是一个字符串?只需使用 JavaScript 对象字面量声明即可。
-
我不知道,但从弹性搜索中获取此字符串
-
字符串的内容是有效的 JavaScript 语法,但不是有效的 JSON 语法。
-
@frank,无论哪种方式都可以
cpu或"cpu" -
不是 JSON 格式。在 JSON 表示法中,属性名称必须用双引号字符引用。
标签: javascript arrays node.js type-conversion