PYTHON ADVANCED - 11 : JSON TUTORIAL

 IN THIS TUTORIAL,  YOU WILL LEARN ABOUT JSON TUTORIAL:

NOTE: TRY ALL TYPES OF CODE WHICH ARE COMMENTED OUT.


import json
#converting python file to json(javascript oriented programming)
# person = {"name":"Shayan", "age": 30, "city": "Patna", "hasChildren": False, "titles": ["Engineer", "Programmer"]}
# personJSON = json.dumps(person, indent=4)#, sort_keys=True)
# print(personJSON)

# with open('person.json', 'w') as file:       #--> file in json
#     json.dump(person, file, indent=4)

#converting json to python file
# person = json.loads(personJSON)
# print(person)

# with open('person.json', 'r') as file:         #--> file reading in python
#     person = json.load(file)
#     print(person)




class User:

    def __init__(self, name, age):
        self.name = name
        self.age = age

user = User('Shayan', 16)

def encode_user(o):
    if isinstance(o, User):
        return{'name': o.name, 'age': o.age, o.__class__.__name__: True}
    else:
        raise TypeError('Object of type user is not JSON serializable')



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}
        return JSONEncoder.default(self, o)


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


def decoder_user(dct):
    if User.__name__ in dct:
        return User(name = dct['name'], age = dct['age'])
    return dct    

# user = json.loads(userJSON)
user = json.loads(userJSON, object_hook=decoder_user)
print(type(user))
print(user.name)

Comments