Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import json
  2.  
  3.  
  4. class Ingredient:
  5. def __init__(self, _name=None, _q=None, _price=None):
  6. self.name = _name
  7. self.quantity = _q
  8. self.price = _price
  9.  
  10. def __str__(self):
  11. return f"{self.name} | {self.quantity} | {self.price}"
  12.  
  13. def to_json(self):
  14. data = json.dumps(vars(self), indent=4)
  15. with open("out_ingz.json", "w+") as f:
  16. f.write(data)
  17. return data
  18.  
  19. def build_object_json(self, data):
  20. self.name = data['name']
  21. self.quantity = data['quantity']
  22. self.price = data['price']
  23.  
  24.  
  25. class Pica:
  26. def __init__(self, ingz=[]):
  27. self.ingredients = ingz
  28.  
  29. def build_object_json(self, data):
  30. for i in data['ingredients']:
  31. j = Ingredient()
  32. j.build_object_json(i)
  33. self.ingredients.append(j)
  34.  
  35. def __str__(self):
  36. results = ''
  37. for i in self.ingredients:
  38. results += f'{i}\n'
  39. return results
  40.  
  41. def to_json(self):
  42. p = self
  43. for i in range(len(p.ingredients)):
  44. p.ingredients[i] = p.ingredients[i].__dict__
  45. data = json.dumps(vars(self), indent=4)
  46. with open("out_pica.json", "w+") as f:
  47. f.write(data)
  48. return data
  49.  
  50. def from_json(self, file):
  51. with open(file, "r") as f:
  52. data = json.loads(f.read())
  53.  
  54. self.build_object_json(data)
  55.  
  56.  
  57.  
  58. if __name__ == "__main__":
  59. p = Pica()
  60. p.from_json('file.json')
  61. print(p)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement