0

I'm trying to parse some JSON data from https://mtgjson.com/json/AllCards.json but I'm not sure how to deal with the way its structured. Here's a snippet of my code:

cards = json.loads(open("AllCards.json", encoding="utf8").read())
for card in cards:
    print(card)

I was expecting "card" to be a dictionary that I could then use to access attributes, for example "card['name']". However all "card" is in this case is a string containing the the key value so I cant use it to access any of the nested attributes. If I print "cards" though, it outputs the entire JSON document including all of the nested attributes.

I also tried accessing them using cards[0] but this gave me a key error.

I'm obviously missing something here but I cant figure out what.

1
  • try cards = json.load("AllCards.json") and for key, value in cards.items() Commented Feb 8, 2019 at 10:24

1 Answer 1

2

Iterating a dictionary will by default iterate its keys.

If you walso want the values, you should iterate dict.items() instead:

import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for key, value in cards.items():
    print(key, value)

value will contain the sub-dict.

It's the same as

import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for key in cards:
    print(key, cards[key])

If you don't care about the key, you can iterate the values directly:

import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for card in cards.values():
    print(card)
Sign up to request clarification or add additional context in comments.

Comments

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.