所以我试图获取列出的 json 中的元素,但我不知道会有多少个元素,具体取决于标签。
我尝试过这个:
tag = "cat"
r = requests.get('https://danbooru.donmai.us/related_tag.json?query=' + tag)
j = json.loads(r.text)
dump = json.dumps(j, indent=2, sort_keys=True)
taglist = []
taglist.append(j["wiki_page_tags"][all][0])
if tag in dump:
print(f"{taglist}")
我正在尝试获得看起来像这样的结果
tag1
tag2
tag3
抱歉,垃圾代码,感谢您的帮助
最佳答案
这就是你要找的吗?
print('\n'.join([x[0] for x in j["wiki_page_tags"]]))
完整示例:
import requests
import json
tag = "cat"
r = requests.get('https://danbooru.donmai.us/related_tag.json?query=' + tag)
j = json.loads(r.text)
dump = json.dumps(j, indent=2, sort_keys=True)
taglist = [x[0] for x in j["wiki_page_tags"]]
print('\n'.join(taglist))
打印:
stuffed_animal
cathead
cheetah
leopard
lion
panther
serval
tiger
black_cat
white_cat
calico
siamese_cat
kitten
cat_focus
too_many_cats
关于python - 有没有办法使用 python 列出 json 中未知数量的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58557715/