read data from json file and import into object in python

Here's an example of how to read data from a JSON file and import it into an object in Python:

main.py
import json

# Open JSON file
with open('data.json') as file:
    data = json.load(file)

# Create an object to hold the data
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create a list of objects
people = []
for item in data:
    person = Person(item['name'], item['age'])
    people.append(person)

# Accessing the data
for person in people:
    print(person.name, person.age)
433 chars
22 lines

In this code, we first use the json module to read the contents of the JSON file into a Python object. Then, we iterate over the contents of the object and create a new Person object for each item in the array. Finally, we can access the data in the object by looping over the list of Person objects and printing out the name and age of each person.

gistlibby LogSnag