gpt4 book ai didi

python - 如何将单引号括在 python 字典周围以使其成为 JSON?

转载 作者:行者123 更新时间:2023-11-28 20:23:34 25 4
gpt4 key购买 nike

我正在尝试从 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

关于python - 如何将单引号括在 python 字典周围以使其成为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20084083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com