yellamo
yellamo

Reputation: 25

Parse JSON Array Response

I am recieving a JSON response back from an API which isnt in the right format to be parsed.

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
  }
  ]
}

Upvotes: 0

Views: 3041

Answers (2)

Tarang Dave
Tarang Dave

Reputation: 331

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/

I've used JSON.parse(<string>) for the case where the response is string.

For other case I just added data key to your response.

Upvotes: 1

4m1r
4m1r

Reputation: 12542

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.

Upvotes: 0

Related Questions