V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Nov 6, 2019 · 4018 views
    This topic created in 2366 days ago, the information mentioned may be changed or developed.

    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 replies    2019-11-11 17:58:40 +08:00
    misaka19000
        1
    misaka19000  
       Nov 6, 2019
    == 是什么意思
    gwy15
        2
    gwy15  
       Nov 6, 2019   ❤️ 6
    看一下 cc['y'].__class__,不一定是 int
    hjq98765
        3
    hjq98765  
    OP
       Nov 6, 2019
    @gwy15 #2 原文:“看一下 cc['y'].__class__,不一定是 int”
    ======
    回复:感谢大佬,破案了😂
    cc 里面的数字是 numpy.int64
    jdhao
        5
    jdhao  
       Nov 6, 2019 via Android
    非 python 原生类型可能不支持 dump,
    ex2vkf
        6
    ex2vkf  
       Nov 6, 2019
    这个坑我也遇到过,也是 numpy 的锅
    xingheng
        7
    xingheng  
       Nov 7, 2019
    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
       Nov 11, 2019
    @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 的内置整数类型
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5394 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 07:33 · PVG 15:33 · LAX 00:33 · JFK 03:33
    ♥ Do have faith in what you're doing.