python - Python 在单个循环中将 Json 数组转换为 Excell 文件
问题描述
我目前正在尝试使用 pandas 将许多 Jsons 数组(通过单个循环)转换为 Excell 文件。
输入:[json 1,json 2, json 3] [json 4, json 5, json 5] 等。
代码:
for t in liste:
response = client.list_discovered_resources(
resourceType=t,
limit=0,
includeDeletedResources=False,
)
if response['resourceIdentifiers']:
print('\n ******************** Resources of Type ',t,'\n')
print(jsbeautifier.beautify(str(response['resourceIdentifiers'])))
# at this point, we have gotten many arrays of jsons displayed in the output.
pd.DataFrame(response['resourceIdentifiers']).to_excel("output.xlsx")
如您所见,每个 ****response['resourceIdentifiers']**** 代表一个 json 数组。当我运行这个循环时,我只得到 Excell 文件中显示的最后一个 jsons 数组(在最后一个循环迭代中产生)。
我希望将数组显示在同一个文件中。
有人可以帮我解决这个问题吗?非常感谢你
解决方案
尝试:
list_of_dfs = []
for t in liste:
response = client.list_discovered_resources(
resourceType=t,
limit=0,
includeDeletedResources=False,
)
if response['resourceIdentifiers']:
print('\n ******************** Resources of Type ', t, '\n')
print(jsbeautifier.beautify(str(response['resourceIdentifiers'])))
list_of_dfs.append(pd.DataFrame(response['resourceIdentifiers']))
final_df = pd.concat(list_of_dfs, ignore_index=True).to_excel("output.xlsx")
如果要将每个数据框保存在单独的工作表中,请使用此选项。
writer = pd.ExcelWriter('data.xlsx',engine='xlsxwriter')
for index, t in enumerate(liste):
response = client.list_discovered_resources(
resourceType=t,
limit=0,
includeDeletedResources=False,
)
if response['resourceIdentifiers']:
print('\n ******************** Resources of Type ', t, '\n')
print(jsbeautifier.beautify(str(response['resourceIdentifiers'])))
df = pd.DataFrame(response['resourceIdentifiers'])
df.to_excel(writer, sheet_name=f'df_{index}', startrow=0, startcol=0, index=False)
writer.save()
推荐阅读
- java - 如何使用带有 Selenium 的 HtmlUnit 驱动程序输入具有 JavaScript 按键功能的密码字段?
- html - 有没有办法拆分一个
标签分成两部分,以便您可以不同的样式?如果没有,那么我可以在网站中将 PNG 转换为 SVG 吗? - terraform - 在 Terraform 中创建 Azure 服务运行状况警报
- c# - 在调用本机方法 MoveWindow 期间闪烁
- sql - SQL:有没有办法从 Redshift 中的 Information Schema 计算 Null 记录
- python - 如何在熊猫的任何列中获取包含特定字符串的所有行的平均值?
- mocking - 如何使用 PHPUnit 模拟 PHP 自己的方法
- python - Python Sqlite3 仅从行打印特定数据
- python - 有没有办法解决我遇到的这个错误?
- asp.net-core - 如何在 ASP .NET Core MVC 表单中使用多个组合框?