You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Normalizr处理API响应中的深度嵌套JSON数组?

解决深度嵌套JSON的规范化问题

嘿,我之前正好处理过这种深度嵌套JSON的规范化需求,给你分享个简单直接的解决方案,完美匹配你想要的输出结构。

首先先明确你的输入和期望输出:

原始嵌套JSON结构

{ 
  "data": { 
    "id": "websites", 
    "type": "table", 
    "attributes": { 
      "data": [ 
        { "name": "facebook.com", "id": "1", ... }, 
        { "name": "google.com", "id": "2", ... }, 
        { "name": "twitter.com", "id": "3", ... } 
      ] 
    } 
  } 
}

期望的规范化输出

{ 
  entities: { 
    "1": { "name": "facebook.com", "id": "1", ... }, 
    "2": { "name": "google.com", "id": "2", ... }, 
    "3": { "name": "twitter.com", "id": "3", ... } 
  }, 
  results: ["1", "2", "3"] 
}

具体实现(以JavaScript为例)

核心思路就是提取出嵌套的数组,然后用reduce方法遍历数组,同时构建entities对象和results数组:

// 假设你的原始数据已经解析为JavaScript对象
const rawData = { 
  "data": { 
    "id": "websites", 
    "type": "table", 
    "attributes": { 
      "data": [ 
        { "name": "facebook.com", "id": "1" }, 
        { "name": "google.com", "id": "2" }, 
        { "name": "twitter.com", "id": "3" } 
      ] 
    } 
  } 
};

// 执行规范化转换
const normalizedData = rawData.data.attributes.data.reduce((acc, item) => {
  // 将当前项以id为键存入entities
  acc.entities[item.id] = item;
  // 将id存入results数组
  acc.results.push(item.id);
  return acc;
}, { entities: {}, results: [] });

console.log(normalizedData);

额外注意事项

  • 重复id处理:如果原始数组中存在重复的id,后面的项会覆盖前面的。如果需要保留所有重复项,可以考虑把entities对应的value改成数组,或者给重复id添加后缀区分。
  • 容错处理:如果某些项可能没有id字段,可以在遍历的时候加个判断,比如:
    if (item.id) {
      acc.entities[item.id] = item;
      acc.results.push(item.id);
    }
    
  • 其他语言实现:如果用Python的话,逻辑类似,用循环遍历数组,手动构建字典和列表即可,比如:
    raw_data = { 
      "data": { 
        "id": "websites", 
        "type": "table", 
        "attributes": { 
          "data": [ 
            {"name": "facebook.com", "id": "1"}, 
            {"name": "google.com", "id": "2"}, 
            {"name": "twitter.com", "id": "3"} 
          ] 
        } 
      } 
    }
    
    normalized_data = {"entities": {}, "results": []}
    for item in raw_data["data"]["attributes"]["data"]:
        normalized_data["entities"][item["id"]] = item
        normalized_data["results"].append(item["id"])
    
    print(normalized_data)
    

内容的提问来源于stack exchange,提问作者Greg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:07:10