|
| 1 | +### JSON, XML Files ### |
| 2 | +import json |
| 3 | +import xml.etree.ElementTree as xml |
| 4 | +import os |
| 5 | + |
| 6 | +info = { |
| 7 | + 'name': 'Mark Doe', |
| 8 | + 'age': 38, |
| 9 | + 'birth_date': '15/18/1965', |
| 10 | + 'languages': ['python', 'javascript', 'java'] |
| 11 | + |
| 12 | +} |
| 13 | + |
| 14 | +#* JSON |
| 15 | +filename_json = 'myjson.json' |
| 16 | + |
| 17 | +with open(filename_json, 'w') as json_file: |
| 18 | + json.dump(info, json_file, indent=2) |
| 19 | + |
| 20 | +with open(filename_json, 'r') as json_file: |
| 21 | + print(json_file.read()) |
| 22 | + |
| 23 | +#* XML |
| 24 | +filename_xml = 'myxml.xml' |
| 25 | + |
| 26 | +root = xml.Element('info') |
| 27 | + |
| 28 | +for key,value in info.items(): |
| 29 | + child = xml.SubElement(root, key) |
| 30 | + if isinstance(value, list): |
| 31 | + for item in value: |
| 32 | + xml.SubElement(child, 'item').text = item |
| 33 | + else: |
| 34 | + child.text = str(value) |
| 35 | + |
| 36 | +tree = xml.ElementTree(root) |
| 37 | +tree.write(filename_xml) |
| 38 | + |
| 39 | +with open(filename_xml, 'r') as xml_file: |
| 40 | + print(xml_file.read()) |
| 41 | + |
| 42 | +#! Optional Challenge |
| 43 | + |
| 44 | +class Data: |
| 45 | + def __init__(self, name, age, birth_date, languages) -> None: |
| 46 | + self.name = name |
| 47 | + self.age = age |
| 48 | + self.birth_date = birth_date |
| 49 | + self.languages = languages |
| 50 | + |
| 51 | +with open(filename_xml, 'r') as xml_file: |
| 52 | + root = xml.fromstring(xml_file.read()) |
| 53 | + name = root.find('name').text |
| 54 | + age = root.find('age').text |
| 55 | + birth_date = root.find('birth_date').text |
| 56 | + languages = [] |
| 57 | + for item in root.find('languages'): |
| 58 | + languages.append(item.text) |
| 59 | + |
| 60 | + my_data = Data(name, age, birth_date, languages) |
| 61 | + print(my_data.__dict__) |
| 62 | + |
| 63 | + |
| 64 | +with open(filename_json, 'r') as json_file: |
| 65 | + info = json.load(json_file) |
| 66 | + my_info = Data(info['name'], info['age'], info['birth_date'], info['languages']) |
| 67 | + print(my_info.__dict__) |
| 68 | + |
| 69 | +os.remove(filename_xml) |
| 70 | +os.remove(filename_json) |
0 commit comments