Create objects from JSON records (dicts)

Viewed 42

I am trying to create a Python class with the data coming from a certain JSON file. The JSON file contains the following list of dictionaries:

    {
  "phonebook": [
    {
      "full_name": "John Doe",
      "address": "QC",
      "phone_number": "+634444444",
      "email": "johnd@xyz.com"
    },
    {
      "full_name": "Jane Doe",
      "address": "LP",
      "phone_number": "+63555555",
      "email": "jannneee@xyz.com"
    },
    {
      "full_name": "Dragon Slayer",
      "address": "VC",
      "phone_number": "+6311111111",
      "email": "dslayer@xyz.com"
    }
  ]
}

I also have a class which is supposed to call all of the values in the JSON file.

import json

# read file
with open('phonebook.json', 'r') as myfile:
    data = myfile.read()

# parse file
phonebook = json.loads(data)

class BaseAccount:
    def __init__(self, full_name, address, phone_number, email):
        self.full_name = full_name
        self.address = address
        self.phone_number = phone_number
        self.email = email

    def display_info(self):
        print("Full Name:", self.full_name)
        print("Address:", self.address)
        print("Telephone Number:", self.phone_number)
        print("E-mail:", self.email)

db = BaseAccount(full_name, address, phone_number, emai)
db.display_info()

I couldn't quite figure out howto call the JSON file into my class. Could you please provide guidance?

1 Answers

From python3.8, dataclasses make this simple:

from dataclasses import dataclass

@dataclass
class BaseAccount:
    full_name: str
    address: str
    phone_number: str
    email: str

    def display_info(self):
        ...
accounts = [BaseAccount(**entry) for entry in data['phonebook']]
accounts[0].display_info()

In the second snippet, I use dictionary unpacking to unpack each record in data["phonebook"] to initialize a new BaseAccount.

Related