省流:换思路解决了
背景:用pandas解析json,使用json_normalize()方法时报错for path data. Must be list or null.
json格式如下
{
"data": {
"page": 0,
"size": 10,
"total": 54,
"data": [
{
"agrType": 1,
"tradeDate": "20221220",
"value": "0.9931628055522528",
"ifShow": "1",
"showName": "银行",
"showYield": 23.064958,
"showYieldDesc": "成立以来收益率"
}
]
},
"msg": "ok",
"retcode": 0
}
使用某鸟网示例代码,出现报错,报错代码:
import pandas as pd
import json
# 使用 Python JSON 模块载入数据
with open('银行1.json','r') as f:
data = json.loads(f.read())
# 展平数据
df_nested_list = pd.json_normalize(data, record_path =['data'])
print(df_nested_list)
报错:json原文 + ‘for path data. Must be list or null.’
本人没查到对应的解决方案,推测是嵌套数据的格式问题,换思路解决:
直接在Dataframe数据时取第二层
import json
import pandas as pd
filepath = '银行6.json'
# 使用 Python JSON 模块载入数据
with open(filepath,'r',encoding='utf-8') as f:
jsondata = json.loads(f.read())
#直接DataFrame数据
json_toDataframe = pd.DataFrame(jsondata['data']['data'])
print(json_toDataframe)