首页 > 解决方案 > 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 数组(在最后一个循环迭代中产生)。

我希望将数组显示在同一个文件中。

有人可以帮我解决这个问题吗?非常感谢你

标签: pythonjsonpandasxlsx

解决方案


尝试:

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()

推荐阅读