如何将单引号包装在python字典中,使其成为JSON



我正在尝试从Python解析JSON。如果我在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

我认为您混淆了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

jsonStr是一个字典,而不是字符串。它已经"加载"了。

您应该能够直接致电

shell_script = jsonStr['hello']
print shell_script

最新更新