-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjson_to_custom_class.py
More file actions
39 lines (31 loc) · 1.05 KB
/
json_to_custom_class.py
File metadata and controls
39 lines (31 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json
class Country:
def __init__(self, name, population, languages):
self.name = name
self.population = population
self.languages = languages
class CountryEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Country):
# JSON object would be a dictionary.
return {
"name": o.name,
"population": o.population,
"languages": o.languages
}
else:
# Base class will raise the TypeError.
return super().default(o)
class CountryDecoder(json.JSONDecoder):
def __init__(self, object_hook=None, *args, **kwargs):
super().__init__(object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, o):
decoded_country = Country(
o.get('name'),
o.get('population'),
o.get('languages'),
)
return decoded_country
with open('canada.json','r') as f:
country_object = json.load(f, cls=CountryDecoder)
print(type(country_object))