如何围绕python字典包装单引号使其成为JSON?

时间:2013-11-19 23:07:20

标签: python json parsing

我正在尝试从JSON解析Python。如果我在json字符串周围使用单引号,我可以正确解析JSON但是如果我删除那个单引号然后它对我不起作用 -

#!/usr/bin/python

import json
# getting JSON string from a method which gives me like this
# so I need to wrap around this dict with single quote to deserialize the JSON
jsonStr = {"hello":"world"} 

j = json.loads(`jsonStr`) #this doesnt work either?
shell_script = j['hello']
print shell_script

所以我的问题是如何围绕单引号包装JSON字符串,以便我能够正确地反序列化它?

我得到的错误 -

$ python jsontest.py
Traceback (most recent call last):
  File "jsontest.py", line 7, in <module>
    j = json.loads('jsonStr')
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

2 个答案:

答案 0 :(得分:5)

我认为您在dumps()loads()

之间混淆了两个不同的概念
jsonStr = {"hello":"world"} 

j = json.loads(json.dumps(jsonStr)) #this should work
shell_script = j['hello']
print shell_script

但是,它是多余的,因为jsonStr已经是一个对象。如果你想尝试loads(),你需要一个有效的json字符串作为输入,如:

jsonStr = '{"hello":"world"}'

j = json.loads(jsonStr) #this should work
shell_script = j['hello']
print shell_script

答案 1 :(得分:3)

jsonStr是字典而不是字符串。它已经“加载”了。

您应该可以直接致电

shell_script = jsonStr['hello']
print shell_script