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
smallpython
V2EX  ›  Python

json.load 方法如何让对象内部都是 str 类型?

  •  
  •   smallpython · Jun 24, 2020 · 1661 views
    This topic created in 2133 days ago, the information mentioned may be changed or developed.

    环境: python2.7.5

    with open('test.json', 'r') as f:
        data = json.load(f)
    

    此时 data 为 {u'中文的键': u'中文的值'}

    里面的键和值都是 unicode 编码的

    能不能让 data 为 {'中文的键': '中文的值'} 就是里面的键和值都是 str 类型

    7 replies    2020-06-24 16:12:51 +08:00
    darer
        1
    darer  
       Jun 24, 2020
    用 python2 你的 str 就是 bytes 啊
    gzfrankie
        2
    gzfrankie  
       Jun 24, 2020
    像楼上说的

    python2 的 string 是 bytes,只能装 ASCII 的字母,装不了中文。

    python3 的 string 就是 python2 的 unicode (直接改了名),然后新弄了 bytes 这个类
    smallpython
        3
    smallpython  
    OP
       Jun 24, 2020
    @gzfrankie

    u'中文的值'.encode('utf-8') 之后的类型不就是 str 类型吗? 也就是字节类型, 我理解 Python2 中 str 和字节码就是一个东西

    而且即便是英文字母 a

    json.load 之后也是 u'a'而不是'a'
    smallpython
        4
    smallpython  
    OP
       Jun 24, 2020
    @gzfrankie 虽然我可以手动把键和值都取出来手动 encode, 但是我希望 json 库自动完成这个过程
    gzfrankie
        5
    gzfrankie  
       Jun 24, 2020   ❤️ 1
    gzfrankie
        6
    gzfrankie  
       Jun 24, 2020
    google 搜索“python 2 json load unicode to string” 出来第一个就是我那个答案
    smallpython
        7
    smallpython  
    OP
       Jun 24, 2020
    @gzfrankie 感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3218 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 98ms · UTC 13:42 · PVG 21:42 · LAX 06:42 · JFK 09:42
    ♥ Do have faith in what you're doing.