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

2024-06-02 08:17:46 发布

您现在位置: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"}]]

起初我以为pandas可以在这里提供帮助,并进行相应的搜索,但作为python/编码的新手,我没能从中得到多少东西。任何帮助或指导都将不胜感激。你知道吗

我希望输出为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"}]```

Tags: nonameinfoagemobileyeshouseowner
2条回答

假设第一个列表总是表示键["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)}

我假设第一个列表总是标题(列名)? 如果是这样的话,也许这样的事情可以奏效。你知道吗

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)

相关问题 更多 >