Python 的 json 包好像有个小 bug?

2019-11-06 18:50:12 +08:00
 hjq98765

json.dumps 执行时会提示 TypeError:

(Pdb) cc == {'y': 17318, 'info_total_periods': 12} 
True

(Pdb) cc is {'y': 17318, 'info_total_periods': 12}
False

(Pdb) json.dumps(cc)
*** TypeError: 17318 is not JSON serializable

(Pdb) json.dumps({'y': 17318, 'info_total_periods': 12})
'{"y": 17318, "info_total_periods": 12}'

为什么会这样?有什么解决方法没?

3167 次点击
所在节点    Python
8 条回复
misaka19000
2019-11-06 18:53:56 +08:00
== 是什么意思
gwy15
2019-11-06 18:54:31 +08:00
看一下 cc['y'].__class__,不一定是 int
hjq98765
2019-11-06 18:59:41 +08:00
@gwy15 #2 原文:“看一下 cc['y'].__class__,不一定是 int”
======
回复:感谢大佬,破案了😂
cc 里面的数字是 numpy.int64
ipwx
2019-11-06 20:11:46 +08:00
jdhao
2019-11-06 21:48:47 +08:00
非 python 原生类型可能不支持 dump,
ex2vkf
2019-11-06 21:51:15 +08:00
这个坑我也遇到过,也是 numpy 的锅
xingheng
2019-11-07 13:00:03 +08:00
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 29 2018, 20:59:26)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin

>>> json.dumps({'y': 17318, 'info_total_periods': 12})
'{"y": 17318, "info_total_periods": 12}'
>>> json.dumps(cc)
'{"y": 17318, "info_total_periods": 12}'
>>>

没有重现
hjq98765
2019-11-11 17:58:40 +08:00
@xingheng #7 原文:“Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 29 2018, 20:59:26)[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin>>> json.dumps({'y': 17318, 'info_total_periods': 12})'{"y": 17318, "info_total_periods": 12}'>>> json.dumps(cc)'{"y": 17318, "info_total_periods": 12}'>>>没有重现”
======
回复:cc 是用其它方式生成的,所以 17318 是 numpy.int64,直接手写那就还是 python 的内置整数类型

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/616951

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX