Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- class Ingredient:
- def __init__(self, _name=None, _weight=None):
- self.name = _name
- self.weight =_weight
- def __init__(self, **entries):
- self.__dict__.update(entries)
- 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.__dict__ = **data
- class Pica:
- def __init__(self, ingz=[]):
- self.ingredients = ingz
- def build_object_json(self, data):
- for i in data['ingredients']:
- self.ingredients.append(Ingredient.build_object_json(i))
- def __str__(self):
- return f'{self.ingredients}'
- 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)
- # for i in data['ingredients']:
- # self.ingredients.append(json.loads(i))
- if __name__ == "__main__":
- # i1 = Ingredient('tomato', 20)
- # i2 = Ingredient('cheese', 50)
- # p = Pica([i1, i2])
- # p.to_json()
- p = Pica()
- p.from_json('out_pica.json')
- print(p)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement