2

I've been researching this for hours now and can't figure out how to get this to work. I have a JSON data file with three categories in every item: deck, description, and name. I'm trying to draw the "name" value for every item 0 - 99 and that save that data to a text file.

Format of json data

I cannot for the life of me figure how how I'm supposed to do it. I load in the data easily enough, and I can print out an individual value with this:


with open('gbdata1.json', 'r') as gbdata1:
    data = json.load(gbdata1)

print(data['results'][0]['name'])

I've tried passing it a list of the numbers I needed:

 names = [0, 1, 2, 3, 4, 5]

   for item in data['results'][names]['name']:
       print(item)

but it says:

TypeError: list indices must be integers or slices, not list

So I tried creating a variable and then just incrementing the variable with a forloop and the += operator, but that didn't work either. I'm a total JSON newbie so if I'm overlooking something very obvious.

1 Answer 1

1

You have got slightly off, what you need to do is iterate the names list and substitute your hardcoded print(data['results'][0]['name']) with iteration variable as:

names = ['1', '2', '3', '4', '5']
for n in names:
    print(data['results'][n]['name']) # You can access other attributes here

Also note that JSON keys are always string, so your names = [1, 2, 3, 4] won't work as it is since it has integer values, either you convert these elements to string or you can cast them to string before accessing the json in the for loop as:

for n in names:
    print(data['results'][str(n)]['name']) # You can access other attributes here
Sign up to request clarification or add additional context in comments.

1 Comment

This was so helpful! Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.