简体   繁体   中英

I want to change API response JSON format

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.

  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);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM