Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python zip() not JSON serializable

Tags:

python

json

My Python dictionary holder includes the following elements:

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

Which throws an error when I do json.dumps(holder):

TypeError: 2007 is not JSON serializable

How can I prevent this error?

like image 928
richie Avatar asked Jul 14 '26 23:07

richie


1 Answers

I added .tolist() and it works;

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]]}]'
like image 85
richie Avatar answered Jul 16 '26 13:07

richie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!