Is there a way to list an unknown number of elements in json using python?

Viewed 106

So i am trying to get elements in a json listed but i don't know how many there will be, depending on the tag.

i tried this:

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}")

and i'm trying to get a result that looks like that

tag1
tag2
tag3

sorry for that trash code, thanks for your help

1 Answers

Is that what you're looking for?

print('\n'.join([x[0] for x in j["wiki_page_tags"]]))

Full example:

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))

prints:

stuffed_animal
cathead
cheetah
leopard
lion
panther
serval
tiger
black_cat
white_cat
calico
siamese_cat
kitten
cat_focus
too_many_cats
Related