推荐学习书目
› 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
wdc63
V2EX  ›  Python

求助, str 转 dic 问题。

  •  
  •   wdc63 · Mar 26, 2017 · 4600 views
    This topic created in 3515 days ago, the information mentioned may be changed or developed.
    a 为 string 类型
    {"ret":0,"msg":"OK","data":[{"code":"000502","name":"绿景控股","total":1900,"cansel":1900,"newprice":17.25,"costprice":17.299},{"code":"002758","name":"华通医药","total":1100,"cansel":1100,"newprice":28.25,"costprice":28.354},{"code":"002778","name":"高科石化","total":800,"cansel":800,"newprice":39.01,"costprice":38.979}]}
    请问如何高效将其转换为 dic 类型
    直接采用 eval()函数失败,错误代码 SyntaxError: invalid character in identifier
    谢谢
    11 replies  •  2017-04-13 18:27:01 +08:00
    seki
    seki
    Mar 26, 2017
    1
    你这个不是 json 吗, json parse
    wdc63
    wdc63
    OP
    Mar 26, 2017
    2
    json.loads()?
    这是 PY 不是 JS
    bazingaterry
    bazingaterry
    Mar 26, 2017 via iPhone
    3
    json.loads
    wdc63
    wdc63
    OP
    Mar 26, 2017
    4
    json.loads(a)返回异常 json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
    bxb100
    bxb100
    Mar 26, 2017 via Android
    5
    string 不能转 dict,用 json 处理
    wdc63
    wdc63
    OP
    Mar 27, 2017
    6
    @bxb100 尝试 json.loads()会抛出异常: Unexpected UTF-8 BOM
    billlee
    billlee
    Mar 27, 2017
    7
    r#6 @wdc63 BOM 问题,那就再试试 json.loads(a[1:]) 或者 json.loads(a[3:])
    wdc63
    wdc63
    OP
    Mar 27, 2017
    8
    找到解决方案了
    if a.startswith(u'\ufeff'):
    a = a.encode('utf8')[3:].decode('utf8')
    然后再 json.loads(a)
    百度到的, text 包含 BOM 字符,在线接口编码的问题吧,谢谢各位。
    wdc63
    wdc63
    OP
    Mar 27, 2017
    9
    @billlee 谢谢
    wycs11
    wycs11
    Mar 27, 2017
    10
    import simplejson
    simplejson.loads(a)
    romanticbao
    romanticbao
    Apr 13, 2017
    11
    这个问题可以先用 repr 把数据打出来看看,根据具体问题进行替换或者采用其他解决方式,然后再用 eval 解决。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3020 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 04:12 · PVG 12:12 · LAX 20:12 · JFK 23:12
    ♥ Do have faith in what you're doing.