Issue
I have a string output as this (its a string return from a Popen command):
p = Popen(ZOO_CMD, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
print output
the variable output
prints:
{
"animals": [
{
"animalCount": 1
}
],
"zooName": "zoo1"
}
I've tried to load the string as such
json_dict = json.loads(output)
print json_dict['animals']
I am getting this traceback
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
Any idea how to fix?
Solution
You try to make it valid JSON and then parse, but that will tend to be error prone unless you have very predictable json errors.
Instead, you could use ast.literal_eval
to safely evaluate it into python:
import ast
s = '''{
"animals": [
{
"animalCount": 1,
}
],
"zooName": 'zoo1'
}'''
ast.literal_eval(s)
Result
{'animals': [{'animalCount': 1}], 'zooName': 'zoo1'}
Answered By - Mark
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.