2012-08-13 89 views
74

我想發送一個簡單的字典從Python的JSON文件,但我不斷收到「TypeError:1425不是JSON序列化」消息。當在Python中序列化JSON時,「TypeError:(Integer)不是JSON序列化」?

import json 
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']} 
afile = open('test.json','w') 
afile.write(json.dumps(alerts,encoding='UTF-8')) 
afile.close() 

如果我添加默認參數,然後將其寫入,但整數值寫入JSON文件作爲字符串,這是不可取的。

afile.write(json.dumps(alerts,encoding='UTF-8',default=str)) 
+0

可能重複[json.dump拋出「TypeError:{...}不是JSON序列化」對看似有效的對象?](http://stackoverflow.com/questions/10872604/json-dump-throwing-typeerror -is-not-json-serializable-on-seemingly-vali) – 2012-08-13 21:12:37

+0

適用於我... – Hamish 2012-08-13 21:12:56

+0

這似乎並不「重複」那個問題。 – 2012-08-13 21:17:55

回答

153

我發現我的問題。問題是我的整數實際上是numpy.int64類型。

+9

我也必須處理這個問題,你的回答指向了正確的方向。我只是想添加[另一個問題的鏈接](http://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types),可以幫助實際解決問題。 – JAC 2013-11-25 17:35:22

+10

如果JSON不可序列化的錯誤信息可能顯示對象的類型,那就好了... – 2015-07-21 19:41:01

+3

[Here](http://stackoverflow.com/a/27050186/310441)是一個整潔的解決方案,它使用自定義串行器。 – Owen 2016-06-17 00:03:49