推荐学习书目
› 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 · Aug 15, 2019 · 2895 views
    This topic created in 2597 days ago, the information mentioned may be changed or developed.

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

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

    4 replies  •  2019-08-16 15:38:28 +08:00
    love
        1
    love  
       Aug 15, 2019   ❤️ 1
    这不是 json 的变种吗,用 json5 之类的库可以解析
    wuwukai007
        2
    wuwukai007  
       Aug 15, 2019   ❤️ 1
    pip install demjson
    demjson.decode(xxx)
    lmingzhi08
        3
    lmingzhi08  
       Aug 15, 2019   ❤️ 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
       Aug 16, 2019
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   851 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:10 · PVG 05:10 · LAX 14:10 · JFK 17:10
    ♥ Do have faith in what you're doing.