0

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
  }
  ]
}
yellamo
  • 25
  • 1
  • 3

2 Answers2

1

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.

Tarang Dave
  • 331
  • 2
  • 11
  • The response would be a string. A server cannot send back a JavaScript object. – Get Off My Lawn Jul 08 '19 at 16:44
  • @GetOffMyLawn, I agree, but the question says response is in JSON with invalid format. for an array enclosed in string JSON.parse seems like the best way to solve the issue. else need more info on the same. – Tarang Dave Jul 08 '19 at 16:49
  • So I tried using JSON.parse and it comes back with unexpected token error. Ultimately I want to get the data into an array and then process each value in a loop. – yellamo Jul 08 '19 at 17:36
  • @yellamo so as shown in the fiddle, is it the same response you getting as mentioned in the part 1? – Tarang Dave Jul 08 '19 at 17:38
  • @yellamo instead of using JSON.parse(), can you try the part 2 of my fiddle, https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse - a similar case – Tarang Dave Jul 08 '19 at 17:56
0

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.

4m1r
  • 12,234
  • 9
  • 46
  • 58
  • 3
    Why not just `let val = {data: await response.json()}`. it's already an array. `Object.assign()` seems like overkill. – Get Off My Lawn Jul 08 '19 at 16:14
  • 1
    I think that was implied. But yes, also why i didn't use async, which may potentially confuse OP. – 4m1r Jul 08 '19 at 16:23