JSON.parse(myArray)失败

时间:2018-09-25 06:45:55

标签: javascript arrays json parsing

我有一个API调用,它以以下格式返回数据:

[
  {
    "children": null,
    "entityDefinition": {
      "id": 0,
      "version": 0,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "entityId": 8280,
      "prettyToString": null
    },
    "state": "NORMAL",
    "nodesPerformanceStateSummary": null,
    "appServerAgentAvailability": {
      "entityId": 8280,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "latest": true,
      "percentage": 100,
      "metricId": 41540
    },
    "machineAgentAvailability": {
      "entityId": 8280,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "latest": true,
      "percentage": 100,
      "metricId": 41548
    }
  }
],
[
  {
    "children": null,
    "entityDefinition": {
      "id": 0,
      "version": 0,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "entityId": 20552,
      "prettyToString": null
    },
    "state": "NORMAL",
    "nodesPerformanceStateSummary": null,
    "appServerAgentAvailability": {
      "entityId": 20552,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "latest": false,
      "percentage": 0,
      "metricId": 41540
    },
    "machineAgentAvailability": {
      "entityId": 20552,
      "entityType": "APPLICATION_COMPONENT_NODE",
      "latest": true,
      "percentage": 100,
      "metricId": 41548
    }
  }
]

当我尝试执行时

JSON.parse(myData).forEach(function(node){
    sails.log.info(node.id);
}

它给了我以下错误:

SyntaxError: Unexpected token , in JSON at position 468
    at JSON.parse (<anonymous>)
    at getListOfAvailableNodes (C:\Users\taaniel.paal\Documents\license-statistics\api\helpers\get-licenses.js:73:14)
    at Request._callback (C:\Users\taaniel.paal\Documents\license-statistics\api\helpers\get-licenses.js:136:30)
    at Request.self.callback (C:\Users\taaniel.paal\Documents\license-statistics\node_modules\request\request.js:185:22)
    at Request.emit (events.js:182:13)
    at Request.EventEmitter.emit (domain.js:442:20)
    at Request.<anonymous> (C:\Users\taaniel.paal\Documents\license-statistics\node_modules\request\request.js:1161:10)
    at Request.emit (events.js:182:13)
    at Request.EventEmitter.emit (domain.js:442:20)
    at IncomingMessage.<anonymous> (C:\Users\taaniel.paal\Documents\license-statistics\node_modules\request\request.js:1083:12)
    at Object.onceWrapper (events.js:273:13)
    at IncomingMessage.emit (events.js:187:15)
    at IncomingMessage.EventEmitter.emit (domain.js:442:20)
    at endReadableNT (_stream_readable.js:1090:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

当数组只有一个元素但有更多元素时,它会失败。也许有人知道解决方法吗?我的意思是,JSON.parse()应该识别数组类型的数据,或者是没有根元素包含此数组的问题,例如{“节点”:[“ x”,“ x”,“ x”]}?我有点困惑,很想从一个聪明的人那里获得一些见识:)

谢谢。

1 个答案:

答案 0 :(得分:4)

这是无效的JSON,您有两个根数组元素。服务器响应必须是固定的。目前,您有类似的内容:

[
"first"
],
[
"second"
]

应该是:

["first", "second"]