V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hjq98765
V2EX  ›  Python

Python 的 json 包好像有个小 bug?

  •  
  •   hjq98765 · 2019-11-06 18:50:12 +08:00 · 3151 次点击
    这是一个创建于 1622 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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}'
    

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

    8 条回复    2019-11-11 17:58:40 +08:00
    misaka19000
        1
    misaka19000  
       2019-11-06 18:53:56 +08:00
    == 是什么意思
    gwy15
        2
    gwy15  
       2019-11-06 18:54:31 +08:00   ❤️ 6
    看一下 cc['y'].__class__,不一定是 int
    hjq98765
        3
    hjq98765  
    OP
       2019-11-06 18:59:41 +08:00
    @gwy15 #2 原文:“看一下 cc['y'].__class__,不一定是 int”
    ======
    回复:感谢大佬,破案了😂
    cc 里面的数字是 numpy.int64
    jdhao
        5
    jdhao  
       2019-11-06 21:48:47 +08:00 via Android
    非 python 原生类型可能不支持 dump,
    ex2vkf
        6
    ex2vkf  
       2019-11-06 21:51:15 +08:00
    这个坑我也遇到过,也是 numpy 的锅
    xingheng
        7
    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
        8
    hjq98765  
    OP
       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 的内置整数类型
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3690 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:42 · PVG 12:42 · LAX 21:42 · JFK 00:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.