Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- class Ingredient:
- def __init__(self, _name=None, _q=None, _price=None):
- self.name = _name
- self.quantity = _q
- self.price = _price
- def __str__(self):
- return f"{self.name} | {self.quantity} | {self.price}"
- def to_json(self):
- data = json.dumps(vars(self), indent=4)
- with open("out_ingz.json", "w+") as f:
- f.write(data)
- return data
- def build_object_json(self, data):
- self.name = data['name']
- self.quantity = data['quantity']
- self.price = data['price']
- class Pica:
- def __init__(self, ingz=[]):
- self.ingredients = ingz
- def build_object_json(self, data):
- for i in data['ingredients']:
- j = Ingredient()
- j.build_object_json(i)
- self.ingredients.append(j)
- def __str__(self):
- results = ''
- for i in self.ingredients:
- results += f'{i}\n'
- return results
- def to_json(self):
- p = self
- for i in range(len(p.ingredients)):
- p.ingredients[i] = p.ingredients[i].__dict__
- data = json.dumps(vars(self), indent=4)
- with open("out_pica.json", "w+") as f:
- f.write(data)
- return data
- def from_json(self, file):
- with open(file, "r") as f:
- data = json.loads(f.read())
- self.build_object_json(data)
- if __name__ == "__main__":
- p = Pica()
- p.from_json('file.json')
- print(p)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement