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

时间:2022-10-29 20:38:26

I am trying to parse JSON from Python. I am able to parse JSON properly if I am using single quote around json string but if I remove that single quote then it doesn't works for me -

我试图从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

So my question is how to wrap that JSON string around single quote so that I am able to deserialize it properly?

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

The error that I get -

我得到的错误 -

$ 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 个解决方案

#1


5  

I think you are confusing two different concepts here between dumps() and loads()

我认为你在dumps()和loads()之间混淆了两个不同的概念

jsonStr = {"hello":"world"} 

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

But yes, it's redundant since jsonStr is already an object. If you wanted to try loads() you need a valid json string as input, like such:

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

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

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

#2


3  

jsonStr is a dictionary not a string. It's already "loaded".

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

You should be able to directly call

你应该可以直接打电话

shell_script = jsonStr['hello']
print shell_script

#1


5  

I think you are confusing two different concepts here between dumps() and loads()

我认为你在dumps()和loads()之间混淆了两个不同的概念

jsonStr = {"hello":"world"} 

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

But yes, it's redundant since jsonStr is already an object. If you wanted to try loads() you need a valid json string as input, like such:

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

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

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

#2


3  

jsonStr is a dictionary not a string. It's already "loaded".

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

You should be able to directly call

你应该可以直接打电话

shell_script = jsonStr['hello']
print shell_script