hnc-vitalii/HNS/Excercises/Json/main.py

62 lines
1.5 KiB
Python
Raw Normal View History

2023-09-12 19:17:10 +02:00
import json
from Shape import Shape
from Circle import Circle
from Rectangle import Rectangle
from Square import Square
def safe_read(obj, property, default_value):
obj == property
def create_shape(json):
if 'type' in json:
shape_type = json['type'].lower()
if shape_type == 'circle':
if 'radius' in json:
obj = Circle(json['radius'])
else:
obj = Circle(0)
elif shape_type == 'square':
if 'side' in json:
obj = Square(json['side'])
else:
obj = Square(0)
elif shape_type == 'rectangle':
obj = Rectangle(json['width'], json['height'])
else:
raise TypeError(f'вот тебе >>>(оIo), а не фигура {shape_type}')
if 'color' in json:
obj.color = json['color']
else:
obj.color = 'unknown'
return obj
def json_to_python():
data_list = []
with open('shapes.json') as lines:
data = json.load(lines)
for i in data['shapes']:
sh1 = create_shape(i)
data_list.append(sh1)
data2 = '{\'shapes\': ' + json.dumps(data_list, default=Shape.convert_to_json) + '}'
with open('Shapes zwei.json', 'w') as f:
json.dump(data2, f)
print('{\'shapes\': ' + json.dumps(data_list, default=Shape.convert_to_json) + '}')
print(json.dumps({'shapes': data_list}, default=Shape.convert_to_json))
json_to_python()