python str转dict_在python中将str转换为dict
實際上,舊版本的rddtool導出ECMA腳本,而不是JSON.根據
this debian bug report升級1.4.8應該給你合適的JSON.另見項目
CHANGELOG:
JSON output of xport is now actually json compilant by its keys
being properly quoted now.
如果你無法升級,你有兩個選擇;要么嘗試重新格式化以應用引用對象鍵標識符,要么使用更寬松的解析器并解析ECMA腳本對象表示法.
>>> import demjson
>>> demjson.decode('''\
... { about: 'RRDtool xport JSON output',
... meta: {
... start: 1401778440,
... step: 60,
... end: 1401778440,
... legend: [
... 'rta_MIN',
... 'rta_MAX',
... 'rta_AVERAGE'
... ]
... },
... data: [
... [ null, null, null ],
... [ null, null, null ],
... [ null, null, null ],
... [ null, null, null ],
... [ null, null, null ],
... [ null, null, null ]
... ]
... }''')
{u'about': u'RRDtool xport JSON output', u'meta': {u'start': 1401778440, u'step': 60, u'end': 1401778440, u'legend': [u'rta_MIN', u'rta_MAX', u'rta_AVERAGE']}, u'data': [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None]]}
修復可以使用正則表達式完成;我將假設所有標識符都在新行上或直接在打開{花括號之后.列表中的單引號必須更改為雙引號;只有在值中沒有嵌入的單引號時,這才有效:
import re
import json
yourtext = re.sub(r'(?:^|(?<={))\s*(\w+)(?=:)', r' "\1"', yourtext, flags=re.M)
yourtext = re.sub(r"'", r'"', yourtext)
data = json.loads(yourtext)
總結
以上是生活随笔為你收集整理的python str转dict_在python中将str转换为dict的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java语言避免了大多数的什么_Java
- 下一篇: python中循环迭代语句_python