首页 > 解决方案 > Python Panda 读取嵌入式 JSON 文件

问题描述

我有一个名为 people 的 csv 文件。

结构如下:

人.csv

"id","name","age","mate"
------------------------
'a1234','Bob',26,"file1234.json"
'a2345','Allen',45,"file2345.json"
'a3456','Kim',18,"file3456.json"
'a4567','Peter',39,"file4567.json"
'a5678','Tim',55,"file5678.json"
#....many more similar records....

JSON 文件示例:

文件 1234.json

{
    "name": "Bob",
    "id": "a1234",
    "age": 26,
    "familymember": [
        {
            "name": "Tim",
            "id": "a5678",
            "parentJson": "file5678.json",
            "age": 55
        },
        {
            "name": "Joe",
            "id": "a9876",
            "parentJson": "file9876.json",
            "age": 19
        }
    ]
}

文件5678.json

{
    "name": "Tim",
    "id": "a5678",
    "age": 55,
    "familymember": [
        {
            "name": "Bob",
            "id": "a1234",
            "parentJson": "file1234.json",
            "age": 22
        },
        {
            "name": "Joe",
            "id": "a9876",
            "parentJson": "file9876.json",
            "age": 20
        }
    ]
}

我的目标是找出 JSON 文件中不一致的年龄。例如:在原始文件中,Bob 是 26,file1234 表示 Bob 是 26,而在 file5678 中,Bob 是 22,这是不一致的。第二个例子是 Joe,在 file1234 中,Joe 是 22,在 file5678 中,Joe 是 20。(id 是每个人的唯一键)

我认为的想法是处理所有 json 文件并生成如下内容:

d=collections.defaultdict(set)
d[id].add(age)

res=[]
for k,v in d.items():
    if len(d[k])>1:
        res.append(k)
return res

具有挑战性的部分实际上是如何展平所有 JSON 文件并将它们保存到字典类型或 Panda 数据帧中,假设你有无限的 CPU 并且能够尽可能多地并行处理,因此所有 JSON 文件都可以并行处理。

在 JSON 中和并行处理 JSON 将是一种高效且优雅的方式。

标签: pythonjsonpandasparallel-processing

解决方案


推荐阅读