我尝试读取JSON数据,然后尝试使用Python将该数据填充到Excel工作表中

9lowa7mx  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(165)

我试过下面的代码
Click on this link to get the json file
进口Pandas当PD

df = pd.read_json('C:\\Users\\rajat.kapoor\\Downloads\\comprehensive JSON.json')
df.to_excel('C:\\Users\\rajat.kapoor\\Desktop\\JsonOutput.xlsx')

但它正在给予

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\construction.py:666, in _extract_index(data)
    664 lengths = list(set(raw_lengths))
    665 if len(lengths) > 1:
--> 666     raise ValueError("All arrays must be of the same length")
    668 if have_dicts:
    669     raise ValueError(
    670         "Mixing dicts with non-Series may lead to ambiguous ordering."
    671     )

ValueError: All arrays must be of the same length

我已经检查了许多关于这个ValueError的帖子,但超出了我的理解范围。希望能为此提供解决方案

7eumitmz

7eumitmz1#

您可以使用pd.json_normalize

import json

data = json.load(open('comprehensive JSON.json'))

# For overallAnalysis
with pd.ExcelWriter('overallAnalysis.xlsx') as writer:
    meta = pd.json_normalize(data['overallAnalysis']).select_dtypes(exclude=object)
    meta.T.to_excel(writer, sheet_name='Metadata', header=False)

    for analytics in ['monthlyAnalytics', 'weeklyAnalytics', 'dailyAnalytics']:
        df = pd.json_normalize(data['overallAnalysis'], analytics)
        df.to_excel(writer, sheet_name=analytics, index=False)

相关问题