簡體   English   中英

如何使用 Pandas 在 python 中將嵌套的 json 數組與它們的父對象平展

[英]how to flatten out nested json arrays with their parent in python using pandas

我需要使用 pandas 模塊在 python 中解析和展平嵌套的 json。

源 JSON:

{
    "people": [{
            "name": "ABC",
            "age": "33",
            "mobile": "44545",
            "location": "hyderabad",
            "interests": [{
                "hobby": "dancing",
                "food": "continental",
                "city": "Paris"
            }]
        },
        {
            "name": "DEF",
            "age": "11",
            "mobile": "12121212",
            "location": "pune",
            "interests": [{
                "hobby": "reading",
                "food": "Pizza",
                "city": "France"
            }]
        }
    ]
}

從上面的源 json 文件中,我需要獲取兩個不同的 json 文件,如下所示:

輸出 JSON 1:

{"name": "ABC", "age": "33", "mobile": "44545", "location": "hyderabad"}
{"name": "DEF", "age": "11","mobile": "12121212", "location": "pune”}

輸出 JSON 2:

{"name": "ABC”, ”interests_hobby”:”dancing”, “interests_food”:”continental”, “interests_city”:”Paris”}
{“name": "DEF”, ”interests_hobby”:”reading”, “interests_food”:”Pizza”, “interests_city”:”France”}

條件是我們必須使用python和pandas模塊。(pd.json_normalize)

首先,您必須打開 json 文件並加載它。 然后,使用命令

df = pd.json_normalize(json_obj, record_path="people")

獲取包含所需字段的 DataFrame。 正如您將看到的,“興趣”字段不會被拆分,但您可以重做這些步驟。

為了獲得具有所需輸出的 ​​json 文件,我建議您

df.to_json(orient='records')

它從 DataFrame 返回一個沒有索引的 json 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM