Theo Esberg
Theo Esberg

Reputation: 3

How do I read an JSON object in python?

Im currently working on a Python Pygame project were I have to work with JSON files. Im trying to read of an JSON file but I just cant get it to print what I want to know.

Here is the JSON file

  "pokemons": {
    "5": {
      "name": "Snivy",
      "type": "Grass",
      "hp": 45,
      "attack": 45,
      "defence": 55,
      "speed": 63,
      "moves": [
        "Tackle",
        "Leer",
        "null",
        "null"
      ],
      "level": 4,
      "xp": 54
    },
    "2": {
      "name": "Tepig",
      "type": "Fire",
      "hp": 65,
      "attack": 63,
      "defence": 45,
      "speed": 45,
      "moves": [
        "Tackle",
        "Tail Whip",
        "Ember",
        "null"
      ],
      "level": 7,
      "xp": 11
    }
  }
} 

Im trying to read the "name", "type", ect from the different "ID's" aka "5" and "2", but I can only make it print "5" and "2" from the "pokemons" array

with open("data.json", "r") as f:
    data = json.load(f)
    for i in data["pokemons"]:
        print(i)

Upvotes: 0

Views: 652

Answers (2)

Jhanvi Patel
Jhanvi Patel

Reputation: 239

My Solution

data = '{"pokemons": {"5": {"name": "Snivy","type": "Grass","hp": 45,"attack": 45,"defence": 55,"speed": 63,"moves": ["Tackle","Leer","null","null"],"level": 4,"xp": 54},"2": {"name": "Tepig","type": "Fire","hp": 65,"attack": 63,"defence": 45,"speed": 45,"moves": ["Tackle","Tail Whip","Ember","null"],"level": 7,"xp": 11}}}}'
datadict = json.loads(data)
dataOfId = datadict['pokemons']
for i in dataOfId:
      print(dataOfId[i]["name"])
      print(dataOfId[i]["type"])

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61519

You've titled this json read from array inside of array python, but you don't have JSON arrays (translated into Python lists) here - you have JSON objects (translated into Python dicts).

for i in data["pokemons"]:

data["pokemons"] is a dict, so iterating over it like this gives you the keys - "5" and "2"`. You can use those to index into the data:

data["pokemons"][i]

That gives you one of the objects (dicts) representing an individual pokemon, from which you can access the name:

data["pokemons"][i]["name"]

Better yet, you can loop over the values of data["pokemons"] directly, instead of the keys:

for pokemon in data["pokemons"].values():
    name = pokemon["name"]

Or you can get both at once using .items(), for example:

for pid, pokemon in data["pokemons"].items():
    # use string formatting to display the pid and matching name together.
    print(f"pokemon number {pid} has name {pokemon['name']}")

Upvotes: 1

Related Questions