繁体   English   中英

难以使用python将嵌套json转换为平面json

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM