python - 函数返回字符串而不是字典
问题描述
我有一个名为“random-words”的包,它每天都会生成一个随机词。
这是主程序:
from random_word import RandomWords
r = RandomWords()
word = r.word_of_the_day()
print( word )
这是输出:
'{"word": "daedal", "definations": [{"source": "gcide", "text": "Cunningly or ingeniously formed or working; skillful; artistic; ingenious.", "note": null, "partOfSpeech": "adjective"}, {"source": "gcide", "text": "Crafty; deceitful.", "note": null, "partOfSpeech": "adjective"}]}'
我知道这是一个简单的问题,但我可以在网上找到任何东西,除了使用exec()
返回类型是字符串的页面,我不能像字典一样使用它。我该如何解决?我尝试使用exec()
,eval()
或转换为list()
,dict()
甚至set()
但没有任何效果。
这是使用时的代码exec()
:
from random_word import RandomWords
r = RandomWords()
word = exec(r.word_of_the_day())
这是错误消息:
Traceback (most recent call last):
File "c:\Users\filip\Desktop\test_words.py", line 4, in <module>
word = exec(r.word_of_the_day())
File "<string>", line 1, in <module>
NameError: name 'null' is not defined
解决方案
你可以使用 json.loads https://docs.python.org/3/library/json.html
import json
string_val = '{"word": "daedal", "definations": [{"k":"v"}]}'
dict_val = json.loads(string_val)
print(dict_val['word'])
输出
daedal
推荐阅读
- typescript - 打字稿 - 强制集合仅包含 2 种类型
- css - 如何在使用css同时更改颜色的同时将鼠标悬停在文本上?
- reactjs - React carousel:为什么图像进入列表视图而不是进入轮播
- google-cloud-platform - GCE startup script fails to run on Ubuntu 18.04
- javascript - 数组对象中的猫鼬更新项目
- image - 总是收到此错误(需要以下参数:-i/--image)
- c# - 验证无效字符串值 Mysql : '\xD9\xBE\xD8\xA7\xDA\xA9
- android - 当设备处于仅负责模式时,在 android studio 中获取 logcats
- java - 通过传递键列表获取 cloudant (couchDB) 数据库文档
- jenkins - Gradle + Jenkins + Artifactory Pro:发布分期和推广