[英]Parse JSON Array Response
I am recieving a JSON response back from an API which isnt in the right format to be parsed. 我收到了来自API的JSON响应,该API的解析格式不正确。
I have tried to add the missing key at the start and it won't allow it. 我试图在开始时添加丢失的密钥,但不允许这样做。
[
{
"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
}
]
I would like this to have the missing key and additional curly bracket like so: 我希望这具有缺少的键和其他大括号,如下所示:
{
"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
}
]
}
Simple object assign? 简单对象分配?
const properResponse = Object.assign({}, {data: [response.json()]});
...assuming response is fetch, or similar with a json method which returns the response object. ...假设响应是获取的,或与返回响应对象的json方法类似。
I'm not sure if the response you're getting is a string or an object. 我不确定您收到的响应是字符串还是对象。
Here's a fiddle that considers both scenarios and logs your expected output to the console. 这是一个小提琴,考虑了两种情况,并将您的预期输出记录到控制台。
https://jsfiddle.net/6yu9ngf5/2/ https://jsfiddle.net/6yu9ngf5/2/
I've used JSON.parse(<string>)
for the case where the response is string. 对于响应为字符串的情况,我使用了
JSON.parse(<string>)
。
For other case I just added data key to your response. 对于其他情况,我只是将数据密钥添加到您的响应中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.