简体   繁体   English

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

[英]Having difficulty in transforming nested json to flat json using python

I have a below API response. 我有下面的API响应。 This is a very small subset which I am pasting here for reference. 这是一个很小的子集,我在这里粘贴以供参考。 there can be 80+ columns on this. 可以有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"}]]

Initially I thought pandas could help here and searched accordingly but as a newbie to python/coding I was not able to get much out of it. 最初,我认为熊猫可以在这里提供帮助并进行相应的搜索,但是作为python / coding的新手,我无法从中受益匪浅。 any help or guidance is appreciated. 任何帮助或指导表示赞赏。

I am expecting output in a JSON key-value pair format such as below. 我期望以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"}]```

I assume that the first list always will be the headers (column names)? 我假设第一个列表始终是标题(列名)? If that is the case, maybe something like this could work. 如果真是这样,也许这样的事情可能起作用。

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)

Assuming that the first list always represents the keys ["name", "age"... etc] and then the subsequent lists represent the actual data/API response then you can construct a dictionary (key pair values) like this. 假设第一个列表始终代表键["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