[英]Having difficulty in transforming nested json to flat json using python
我有下面的API響應。 這是一個很小的子集,我在這里粘貼以供參考。 可以有80多個列。
[["name","age","children","city", "info"], ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}],
["Mary", "43", ["Phil", "Marshall", "Emily"], {"mobile":"yes","house_owner":"yes", "own_stocks": "yes"}],
["Drew", "21", [], {"mobile":"yes","house_owner":"no", "investor":"yes"}]]
最初,我認為熊貓可以在這里提供幫助並進行相應的搜索,但是作為python / coding的新手,我無法從中受益匪淺。 任何幫助或指導表示贊賞。
我期望以JSON鍵/值對格式輸出,如下所示。
{"name":"Mary", "age":"43", "children":["Phil", "Marshall", "Emily"],"info_mobile":"yes","info_house_owner":"yes", "info_own_stocks": "yes"},
{"name":"Drew", "age":"21", "children":[], "info_mobile":"yes","info_house_owner":"no", "info_investor":"yes"}]```
我假設第一個列表始終是標題(列名)? 如果真是這樣,也許這樣的事情可能起作用。
import pandas as pd
data = [["name", "age", "children", "info"], ["Ned", 40, ["Arya", "Rob"], {"dead": "yes", "winter is coming": "yes"}]]
headers = data[0]
data = data[1:]
df = pd.DataFrame(data, columns=headers)
df_json = df.to_json()
print(df)
假設第一個列表始終代表鍵["name", "age"... etc]
,然后后續的列表代表實際的數據/ API響應,則可以像這樣構造一個字典(鍵對值)。
keys = ["name", "age", "children", "info"]
api_response = ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}]
data_dict = {k: v for k, v in zip(keys, api_response)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.