Python zip() 无法序列化为 JSON
我的 Python 字典 holder
包含以下元素:
'sr': map(list,zip(df['year'].values,df['sr'].values)),
'nom': map(list,zip(df['year'].values,df['nom'].values))} for df in np.array_split(data, len(data['cou'].unique()))]
当我执行 json.dumps(holder)
时,会出现错误:
TypeError: 2007 is not JSON serializable
我该如何避免这个错误呢?
1 个回答
4
我加上了 .tolist()
这个东西,现在可以用了。
holder = [{'cou':df['cou'].unique()[0],
'region':df['cou'].unique()[0],
'value': map(list,zip(df['year'].values.tolist(),df['value'].values.tolist())),
'sr': map(list,zip(df['year'].values.tolist(),df['sr'].values.tolist())),
'nom': map(list,zip(df['year'].values.tolist(),df['nom'].values.tolist()))} for df in np.array_split(data, len(data['cou'].unique()))]
json.dumps(holder)
'[{"sr": [[2007, 8], [2008, 7], [2009, 6], [2010, 5]], "region": "China", "cou": "China", "value": [[2007, 1], [2008, 2], [2009, 3], [2010, 4]], "nom": [[2007, 1], [2008, 3], [2009, 2], [2010, 5]]}, {"sr": [[2007, 4], [2008, 3], [2009, 2], [2010, 1]], "region": "England", "cou": "England", "value": [[2007, 5], [2008, 6], [2009, 7], [2010, 8]], "nom": [[2007, 4], [2008, 6], [2009, 7], [2010, 5]]}]'