首页 > 解决方案 > 获取python中“子文件夹”中的json值

问题描述

我必须从 json 文件中获取数据,但我需要的值是更大值的子值。(这有点难以解释)。基本上文件看起来像这样:

{
    "records": [
        {
            "id": "reck8UMt9Kd2C5o05",
            "fields": {
                "start_date": "2021-06-02T22:00:00.000Z",
                "ei_ready": true,
                "⚙️rw_ecpm": 12.5,
                "adset_id": "60bf50a4321707001074c113",
                "⚙️dyn_standard": 65,
                "production_status": "Prozessiert",
                "copy2": "Vom Samstag, 10. April, ab 18 Uhr, bis Donnerstag, 22. April 2021",
                "copy1": "Fahrplanänderungen Brugg AG-Turgi-Baden."
            },
            "createdTime": "2021-06-04T07:17:08.000Z"
        }
    ]
}

如何从这个 json 文件中只获取 copy2 或 copy1 值?我尝试过这样的事情,但它不起作用。就像我必须在文件夹中的文件夹中查找文件:

copy1 = (ATdata["records"],{},{"fields"},["copy1"])
print("copy1")# and only copy1 not anything else

谢谢

标签: pythonjson

解决方案


您的 json 的 records 键是包含字典列表的根键,因此 records [0] 是您想要的文档。

现在您想要的文档在字段中再次包含一个字典,并且您想要的键是 copy1 或 copy2 在其中,因此您可以像这样访问它:

j = {your json given above}
j["records"] [0]["fields"]["copy1"]
j["records"] [0]["fields"]["copy2"]

现在,如果您在该记录列表中有多个文档。你必须这样做:

Copy1=[] #to store all copy1 here
Copy2=[]
for i in j["records"]:
    Copy1.append(i["fields"]["copy1"])
    Copy2.append(i["fields"]["copy2"]) #here i is each document

推荐阅读