【问题标题】:I want to change API response JSON format我想更改 API 响应 JSON 格式
【发布时间】:2021-03-02 10:56:12
【问题描述】:

这是我从 API 得到的实际响应,我想转换下面的 JSON 格式

发件人:

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

收件人:

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

如何移除 Object 之间的数组。

【问题讨论】:

  • 先解析然后你可以在数据上使用flat
  • 您的 JSON 无效。 "filename": "attachment_0.png", 是错误的。不允许使用逗号。 "data": 也是错误的。你不能从属性开始。

标签: javascript arrays json react-native


【解决方案1】:
  1. 将 JSON 转换为 JavaScript
  2. 扁平化数组
  3. 将 JavaScript 转换为 Json
const json = JSON.stringify(JSON.parse(data).flat())

我必须修复你的 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);

【讨论】:

    【解决方案2】:

    你想要的一切都在 data 数组的第一个元素中,所以只需索引它。

    obj = JSON.parse(response);
    obj.data = obj.data[0];
    

    【讨论】:

      【解决方案3】:

      如果反应从来都不是很大,你总是可以这样做

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

      否则,看看here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-25
        • 2016-04-04
        相关资源
        最近更新 更多