-2

Here is actual response I got from API, I want to convert the below JSON format

From:

"data": [
    [
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 100793,
        "filename": "attachment_0.png",
      }
    ],
    [
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 6343078,
        "filename": "attachment_1.png"
      }
    ]
  ]

To:

"data": [
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 100793,
        "filename": "attachment_0.png",
      },
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 6343078,
        "filename": "attachment_1.png"
      }
  ]

How do I remove the array between the Object.

Barmar
  • 741,623
  • 53
  • 500
  • 612

3 Answers3

1
  1. Convert JSON to JavaScript
  2. Flatten the array
  3. Convert JavaScript to Json
const json = JSON.stringify(JSON.parse(data).flat())

I had to fix your JSON:

const data = `[
    [
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 100793,
        "filename": "attachment_0.png"
      }
    ],
    [
      {
        "isFile": "true",
        "fileType": "image",
        "filesize": 6343078,
        "filename": "attachment_1.png"
      }
    ]
  ]`
  
const json = JSON.stringify(JSON.parse(data).flat());
console.log(json);
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
0

Everything you want is in the first element of the data array, so just index it.

obj = JSON.parse(response);
obj.data = obj.data[0];
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If the response is never really big you can always do

let data = JSON.parse(response);
for (el in data) {
    el = el[0]
}

otherwise, have a look here

Don Diego
  • 1,309
  • 3
  • 23
  • 46