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

如何将嵌套JSON/XML数据集转换为元组列表?求通用实现方法

嵌套JSON数据集转元组列表的通用实现

问题描述

需要将嵌套的JSON数据集转换为元组列表,示例输入如下:

[
  {
    "id": "978-0062562",
    "name": "The Hidden Oracle",
    "author": "Rick Riordan",
    "details": [
      {
        "genre": "Fantasy",
        "published_year": 2017,
        "publisher": "Disney-Hyperion"
      },
      {
        "genre": "Fantasy",
        "published_year": 2018,
        "publisher": "Disney-Hyperion"
      }
    ]
  },
  {
    "id": "978-148474",
    "name": "Magnus Chase and the Gods of Asgard",
    "author": "Rick Riordan",
    "details": [
      {
        "genre": "Fantasy",
        "published_year": 2016,
        "publisher": "Disney-Hyperion"
      }
    ]
  }
]

期望输出:

[('978-0062562', 'The Hidden Oracle', 'Rick Riordan', [('Fantasy', 2017, 'Disney-Hyperion'), ('Fantasy', 2018, 'Disney-Hyperion')]), ('978-148474', 'Magnus Chase and the Gods of Asgard', 'Rick Riordan', [('Fantasy', 2016, 'Disney-Hyperion')])]

此前尝试递归遍历转换但未成功,需要通用的实现方法。

解决方案

方法1:针对固定结构的快速转换

如果数据集结构固定(顶层为书籍列表,每本书包含id、name、author、details字段,details为字典列表),可以直接按字段提取转换:

import json

# 读取JSON文件
with open('books.json', 'r') as f:
    data = json.load(f)

def convert_book(book):
    # 将details中的每个字典转为元组
    details_tuples = [tuple(detail.values()) for detail in book['details']]
    # 返回书籍信息的元组
    return (book['id'], book['name'], book['author'], details_tuples)

# 转换整个数据集
result = [convert_book(book) for book in data]
print(result)

方法2:通用递归转换(适配任意嵌套结构)

如果需要处理不同层级的嵌套数据集,递归方法可以自动识别并转换列表、字典结构,同时支持指定字典转元组的键顺序:

import json

def convert_to_tuples(data, dict_key_order=None):
    """
    递归将嵌套JSON数据转换为元组列表
    :param data: 输入的JSON数据(列表/字典)
    :param dict_key_order: 可选,指定字典转元组的键顺序,如['id', 'name', 'author', 'details']
    """
    if isinstance(data, list):
        return [convert_to_tuples(item, dict_key_order) for item in data]
    elif isinstance(data, dict):
        if dict_key_order:
            # 按指定顺序提取值并转换
            values = [convert_to_tuples(data[key], dict_key_order) for key in dict_key_order if key in data]
        else:
            # 默认按字典键的插入顺序(Python 3.7+)转换
            values = [convert_to_tuples(value, dict_key_order) for _, value in data.items()]
        return tuple(values)
    else:
        # 非容器类型直接返回原数据
        return data

# 读取JSON文件
with open('books.json', 'r') as f:
    data = json.load(f)

# 指定键顺序以匹配示例输出
key_order = ['id', 'name', 'author', 'details']
result = convert_to_tuples(data, key_order)
print(result)

这个递归函数可适配任意嵌套层级的JSON结构,同时通过dict_key_order参数保证输出元组的字段顺序符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:00:27