首页 > 解决方案 > 解析 JSON 数组响应

问题描述

我从一个 API 收到的 JSON 响应返回的格式不正确,无法解析。

我试图在开始时添加缺少的密钥,但它不允许。

[
  {
    "deviceId": "9092eab10f4",
    "name": "temperature",
    "timestamp": "2017-06-13T13:19:59.673Z",
    "value": 21.5
  },
  {
    "deviceId": "9092eab10f4",
    "name": "temperature",
    "timestamp": "2017-06-13T13:19:59.673Z",
    "value": 21.5
  }
]

我希望它有丢失的键和额外的大括号,如下所示:

{
  "data": [
  {
    "deviceId": "9092eab10f4",
    "name": "temperature",
    "timestamp": "2017-06-13T13:19:59.673Z",
    "value": 21.5
  },
  {
    "deviceId": "9092eab10f4",
    "name": "temperature",
    "timestamp": "2017-06-13T13:19:59.673Z",
    "value": 21.5
  }
  ]
}

标签: javascriptarraysjson

解决方案


简单的对象分配?

const properResponse = Object.assign({}, {data: [response.json()]});

...假设响应是 fetch,或者与返回响应对象的 json 方法类似。


推荐阅读