如何在python中读取JSON对象?

时间:2020-04-26 22:05:45

标签: python json

我目前正在处理Python Pygame项目,因为我必须使用JSON文件。我试图读取一个JSON文件,但我无法获取它来打印我想知道的内容。

这是JSON文件

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

我试图从不同的“ ID”(也称为“ 5”和“ 2”)中读取“名称”,“类型”等,但是我只能从“口袋妖怪”中打印“ 5”和“ 2” “数组

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

2 个答案:

答案 0 :(得分:1)

您已将此标题命名为json read from array inside of array python,但这里没有JSON数组(已转换为Python列表)-您具有JSON对象(已转换为Python字典)。

for i in data["pokemons"]:

data["pokemons"]是字典,因此像这样遍历它可以为您提供密钥-"5"和“ 2”`。您可以使用它们来索引数据:

data["pokemons"][i]

这为您提供了代表单个宠物小精灵的对象(字典)之一,您可以从中访问名称:

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

更好的是,您可以直接遍历data["pokemons"]的值而不是键:

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

或者您可以使用.items()一次获得两者,例如:

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

答案 1 :(得分:1)

我的解决方案

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"])
相关问题