如何将python字典中的单引号包装成JSON?

如何将python字典中的单引号包装成JSON?,python,json,parsing,Python,Json,Parsing,我试图从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

我试图从
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
$python jsontest.py
回溯(最近一次呼叫最后一次):
文件“jsontest.py”,第7行,在
j=json.load('jsonStr')
文件“/usr/lib/python2.7/json/_init__.py”,第326行,加载
返回\u默认\u解码器。解码
文件“/usr/lib/python2.7/json/decoder.py”,第366行,在decode中
obj,end=self.raw\u decode(s,idx=\u w(s,0.end())
原始解码中的文件“/usr/lib/python2.7/json/decoder.py”,第384行
raise VALUERROR(“无法解码JSON对象”)
ValueError:无法解码任何JSON对象

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

你应该可以直接打电话

shell_script = jsonStr['hello']
print shell_script

我认为您在这里混淆了
dumps()
loads()

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

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

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

在您的代码示例中,
jsonStr
已经是一个字典。如果它像绳子一样,它就会工作。您不能简单地将一个值放在引号内,然后用它生成一个字符串。
jsonStr = '{"hello":"world"}'

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