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

str 转 dict 的问题

  •  
  •   BryceBu · 2019-08-15 12:00:22 +08:00 · 1571 次点击
    这是一个创建于 1717 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现有 str: {a: {b: '值 1', c: 0, d: '值 2', e: '1', f: [1,2,3]}

    好像因为其中的 key 都没有引号,我用 eval() 和 ast.literal_eval() 都转换失败了

    4 条回复    2019-08-16 15:38:28 +08:00
    love
        1
    love  
       2019-08-15 12:21:40 +08:00   ❤️ 1
    这不是 json 的变种吗,用 json5 之类的库可以解析
    wuwukai007
        2
    wuwukai007  
       2019-08-15 16:09:22 +08:00   ❤️ 1
    pip install demjson
    demjson.decode(xxx)
    lmingzhi08
        3
    lmingzhi08  
       2019-08-15 17:12:04 +08:00   ❤️ 1
    # 或者使用正则
    import re
    astr = '''{a: {b: '值 1', c: 0, d: '值 2', e: '1', f:[1,2,3]}}'''
    eval(re.sub(r'\s*(\w+)\s*:', r"'\1':", astr))
    # {'a': {'b': '值 1', 'c': 0, 'd': '值 2', 'e': '1', 'f': [1, 2, 3]}}

    import demjson
    demjson.decode(astr)
    BryceBu
        4
    BryceBu  
    OP
       2019-08-16 15:38:28 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2659 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:28 · PVG 12:28 · LAX 21:28 · JFK 00:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.