我的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
如何防止此错误?
答案 0 :(得分: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]]}]'