Read json with multiple root elements as dict

Advertisements

Im trying to read a json file with multiple root elements into python as a dict, but when I do this it comes in as a list. Do I have to change the json formatting? If so, how? If I remove the [] from the json file it wont read the other root elements, only the first one.

Here is my json file:

    [{
      "id": 1,
      "first_name": "Jeanette",
      "last_name": "Penddreth",
      "email": "jpenddreth0@census.gov",
      "gender": "Female",
      "ip_address": "26.58.193.2"
    },{
      "id": 2,
      "first_name": "Giavani",
      "last_name": "Frediani",
      "email": "gfrediani1@senate.gov",
      "gender": "Male",
      "ip_address": "229.179.4.212"
    },{
      "id": 3,
      "first_name": "Noell",
      "last_name": "Bea",
      "email": "nbea2@imageshack.us",
      "gender": "Female",
      "ip_address": "180.66.162.255"
    },{
      "id": 4,
      "first_name": "Willard",
      "last_name": "Valek",
      "email": "wvalek3@vk.com",
      "gender": "Male",
      "ip_address": "67.76.188.26"
    }]

Here is my python code:

    import json

    with open("data.json", "r") as file:
        data = file.read()
        json_obj = json.loads(data)

    print(type(json_obj))

All help appreciated.

Thanks,

Tried:

import json

with open("data.json", "r") as file:
    data = file.read()
    json_obj = json.loads(data)

print(type(json_obj))

Output is

<class ‘list’>

Expected:

<class ‘dict’>

>Solution :

In order for the top level to be a dictionary, the JSON file must contain keys for each object. You could perform this after reading the top level array, or change the content of your JSON file:

Converting list to a dict:

json_obj = { d.pop("id"):d for d in json_obj } # making the "id" the key

Or changing the format of the file:

{ "1":{
  "id": 1,
  "first_name": "Jeanette",
  "last_name": "Penddreth",
  "email": "jpenddreth0@census.gov",
  "gender": "Female",
  "ip_address": "26.58.193.2"
  },
  "2":{
  "id": 2,
  "first_name": "Giavani",
  "last_name": "Frediani",
  "email": "gfrediani1@senate.gov",
  "gender": "Male",
  "ip_address": "229.179.4.212"
  },
  "3":{
  "id": 3,
  "first_name": "Noell",
  "last_name": "Bea",
  "email": "nbea2@imageshack.us",
  "gender": "Female",
  "ip_address": "180.66.162.255"
  },
  "4":{
  "id": 4,
  "first_name": "Willard",
  "last_name": "Valek",
  "email": "wvalek3@vk.com",
  "gender": "Male",
  "ip_address": "67.76.188.26"
}}

Leave a ReplyCancel reply