如何将json嵌套数据集或xml嵌套数据集转换为元组列表?

xxe27gdn  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(43)

正如标题所示,下面的测试用例可以给予我的任务是什么。假设我有一个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')])]


我想找到一种更通用的方法,它可能适用于任何类似的数据集。我甚至尝试递归地迭代内容以达到某些东西,但失败了。

jobtbby3

jobtbby31#

下面是递归方法来转换列表:

lst = [
    {
        "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"}
        ],
    },
]

def convert(obj):
    if isinstance(obj, list):
        return [convert(v) for v in obj]
    elif isinstance(obj, dict):
        return tuple(convert(v) for v in obj.values())
    else:
        return obj

print(convert(lst))

字符串
印刷品:

[
    (
        "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")],
    ),
]

相关问题