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

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

  •  
  •   smallpython · 2020-06-24 15:22:05 +08:00 · 1198 次点击
    这是一个创建于 1409 天前的主题,其中的信息可能已经有所发展或是发生改变。

    环境: python2.7.5

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

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

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

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

    7 条回复    2020-06-24 16:12:51 +08:00
    darer
        1
    darer  
       2020-06-24 15:27:14 +08:00
    用 python2 你的 str 就是 bytes 啊
    gzfrankie
        2
    gzfrankie  
       2020-06-24 15:31:38 +08:00
    像楼上说的

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

    python3 的 string 就是 python2 的 unicode (直接改了名),然后新弄了 bytes 这个类
    smallpython
        3
    smallpython  
    OP
       2020-06-24 15:38:21 +08:00
    @gzfrankie

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

    而且即便是英文字母 a

    json.load 之后也是 u'a'而不是'a'
    smallpython
        4
    smallpython  
    OP
       2020-06-24 15:39:27 +08:00
    @gzfrankie 虽然我可以手动把键和值都取出来手动 encode, 但是我希望 json 库自动完成这个过程
    gzfrankie
        5
    gzfrankie  
       2020-06-24 15:53:57 +08:00   ❤️ 1
    gzfrankie
        6
    gzfrankie  
       2020-06-24 15:55:45 +08:00
    google 搜索“python 2 json load unicode to string” 出来第一个就是我那个答案
    smallpython
        7
    smallpython  
    OP
       2020-06-24 16:12:51 +08:00
    @gzfrankie 感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2151 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:49 · PVG 23:49 · LAX 08:49 · JFK 11:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.