Home > Mobile >  How do I turn JSON Objects into a dict?
How do I turn JSON Objects into a dict?

Time:02-27

Working on a freshwater fish conservation project. I scraped a JSON file that looks like this:

{
  "fish": [
    {
      "id": 0,
      "n": "NO INFORMATION",
      "a": "NONE",
      "i": "none.png"
    },
    {
      "id": 1,
      "n": "Hampala barb",
      "a": "Hampala macrolepidota",
      "i": "hampala.png"
    },
    {
      "id": 2,
      "n": "Giant snakehead",
      "a": "Channa micropeltes",
      "i": "toman.png"
    },
    {
      "id": 3,
      "n": "Clown featherback",
      "a": "Chitala ornata",
      "i": "belida.png"
    }
  ]
}

And I'm trying to extract the keys "id" and "a" into a python dictionary like this:

fish_id = {
  0 : "NONE",
  1 : "Hampala macrolepidota",
  2 : "Channa micropeltes",
  3 : "Chitala ornata"
}

CodePudding user response:

import json

data = """{
  "fish": [
    {
      "id": 0,
      "n": "NO INFORMATION",
      "a": "NONE",
      "i": "none.png"
    },
    {
      "id": 1,
      "n": "Hampala barb",
      "a": "Hampala macrolepidota",
      "i": "hampala.png"
    },
    {
      "id": 2,
      "n": "Giant snakehead",
      "a": "Channa micropeltes",
      "i": "toman.png"
    },
    {
      "id": 3,
      "n": "Clown featherback",
      "a": "Chitala ornata",
      "i": "belida.png"
    }
  ]
}"""

data_dict = json.loads(data)
fish_id = {}
for item in data_dict["fish"]:
    fish_id[item["id"]] = item["a"]

print(fish_id)

CodePudding user response:

First create a fish.json file and get your JSON file;

with open('fish.json') as json_file:
    data = json.load(json_file)

Then, take your fishes;

fish1 = data['fish'][0]
fish2 = data['fish'][1]
fish3 = data['fish'][2]
fish4 = data['fish'][3]

After that take only values for each, because you want to create a dictionary only from values;

value_list1=list(fish1.values())
value_list2=list(fish2.values())
value_list3=list(fish3.values())
value_list4=list(fish4.values())

Finally, create fish_id dictionary;

fish_id = {
    f"{value_list1[0]}" : f"{value_list1[2]}",
    f"{value_list2[0]}" : f"{value_list2[2]}",
    f"{value_list3[0]}" : f"{value_list3[2]}",
    f"{value_list4[0]}" : f"{value_list4[2]}",
}

if you run;

print(fish_id)

Result will be like below, but if you can use for loops, it can be more effective.

{'0': 'NONE', '1': 'Hampala macrolepidota', '2': 'Channa micropeltes', '3': 'Chitala ornata'}

  • Related