import json
person = {'name':'John','age':28,'city':'New York','hasChildren':False}

personJson = json.dumps(person,indent=4,separators=(':','='),sort_keys=True)
print(personJson)

with open('res/person.json', 'w') as f:
    json.dump(person,f,indent=4)


person = {'name':'John','age':28,'city':'New York','hasChildren':False}

personJson = json.dumps(person)
person_new = json.loads(personJson)
print(person_new)


with open('res/person.json', 'r') as f:
    person = json.load(f)
    print(json) 


class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age
user = User('albert',29)
def encode_user(o):
    if isinstance(o,User):
        return {'name':o.name,'age':o.age,o.__class__.__name__:True}
    else:
        raise TypeError('is not JSON serializable')
userJSON = json.dumps(user,default=encode_user)
print(userJSON)

from json import JSONEncoder
class UserEncoder(JSONEncoder):
    def default(self,o):
        if isinstance(o,User):
            return {'name':o.name,'age':o.age,o.__class__.__name__:True}

userJSON = json.dumps(user,cls=UserEncoder)
print(userJSON)

userJSON2 = UserEncoder().encode(user)
print(userJSON2)

def decode_user(dct):
    if User.__name__ in dct:
        return User(name=dct['name'],age=dct['age'])
    return dct
user = json.loads(userJSON,object_hook=decode_user)
print(type(user))
print(user.name)
import json
person = {'name':'John','age':28,'city':'New York','hasChildren':False}

personJson = json.dumps(person,indent=4,separators=(':','='),sort_keys=True)
print(personJson)

with open('res/person.json', 'w') as f:
    json.dump(person,f,indent=4)


person = {'name':'John','age':28,'city':'New York','hasChildren':False}

personJson = json.dumps(person)
person_new = json.loads(personJson)
print(person_new)


with open('res/person.json', 'r') as f:
    person = json.load(f)
    print(json) 


class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age
user = User('albert',29)
def encode_user(o):
    if isinstance(o,User):
        return {'name':o.name,'age':o.age,o.__class__.__name__:True}
    else:
        raise TypeError('is not JSON serializable')
userJSON = json.dumps(user,default=encode_user)
print(userJSON)

from json import JSONEncoder
class UserEncoder(JSONEncoder):
    def default(self,o):
        if isinstance(o,User):
            return {'name':o.name,'age':o.age,o.__class__.__name__:True}

userJSON = json.dumps(user,cls=UserEncoder)
print(userJSON)

userJSON2 = UserEncoder().encode(user)
print(userJSON2)

def decode_user(dct):
    if User.__name__ in dct:
        return User(name=dct['name'],age=dct['age'])
    return dct
user = json.loads(userJSON,object_hook=decode_user)
print(type(user))
print(user.name)