如何将带有字典的字符串转换为实际的字典对象?
How to convert string with dict into actual dict object?
我有这样的字符串输出(它是来自 Popen 命令的字符串 return):
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
知道如何解决吗?
您尝试使其有效 JSON 然后进行解析,但这往往很容易出错,除非您有非常可预测的 json 错误。
相反,您可以使用 ast.literal_eval
安全地将其计算为 python:
import ast
s = '''{
"animals": [
{
"animalCount": 1,
}
],
"zooName": 'zoo1'
}'''
ast.literal_eval(s)
结果
{'animals': [{'animalCount': 1}], 'zooName': 'zoo1'}
我有这样的字符串输出(它是来自 Popen 命令的字符串 return):
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
知道如何解决吗?
您尝试使其有效 JSON 然后进行解析,但这往往很容易出错,除非您有非常可预测的 json 错误。
相反,您可以使用 ast.literal_eval
安全地将其计算为 python:
import ast
s = '''{
"animals": [
{
"animalCount": 1,
}
],
"zooName": 'zoo1'
}'''
ast.literal_eval(s)
结果
{'animals': [{'animalCount': 1}], 'zooName': 'zoo1'}