如何将带有字典的字符串转换为实际的字典对象?

时间:2019-07-05 22:36:10

标签: python json python-2.x

我有一个这样的字符串输出(它是从Popen命令返回的字符串):

p = Popen(ZOO_CMD, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
print output

变量output打印:

{
  "animals": [
    {
      "animalCount": 1
    }
  ],
  "zooName": "zoo1"
}

我试图这样加载字符串

json_dict = json.loads(output)
print json_dict['animals']

我正在得到这个追溯

Traceback (most recent call last):
  File "./zoo_dump", line 44, in <module>
    json_dict = json.loads(output)
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

任何想法如何解决?

1 个答案:

答案 0 :(得分:2)

您尝试使其成为有效的JSON,然后进行解析,但是除非您有非常可预测的JSON错误,否则这往往容易出错。

相反,您可以使用ast.literal_eval将其安全地评估为python:

import ast 

s = '''{
  "animals": [
    {
      "animalCount": 1,
    }
  ],
  "zooName": 'zoo1'
}'''

ast.literal_eval(s)

结果

{'animals': [{'animalCount': 1}], 'zooName': 'zoo1'}