DEV Community

Cover image for JSON to python object
Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

JSON to python object

This is a very fast how-to encode and decode python objects to json.

  • For decoding we will use the parameter object_hook. With it, we can pass a function to the json.loads function.
  • For encoding we will use a Custom JSON encoder.

Mapping incoming object with standard library

import json
my_json_str = '{"name":"John", "age":31, "city":"New York"}'
my_dict_json = json.loads(my_json_str)
# output: {"name":"John", "age":31, "city":"New York"}
Enter fullscreen mode Exit fullscreen mode

Now, with a dictionary we have different approaches for making the object mapping

Mapping approach with dict and constructor´s parameters

class MyObject(object):
    def __init__(self, age:int, city:str, name:str): = name
        self.age = age = city

    def __repr__(self):
        return f"{} {self.age} {}"

my_obj = json.loads(my_json_str, object_hook=lambda data: MyObject(**data))


# output: John 31 New York
Enter fullscreen mode Exit fullscreen mode

Decode class with a Custom encoder

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if issubclass(type(obj), MyObject):
            return json.dumps(obj.__dict__, default=lambda _: None)
        return json.JSONEncoder.default(self, obj)     

obj_str = json.dumps(my_obj, default=CustomJSONEncoder().default)
#output: "{\"name\": \"John\", \"age\": 31, \"city\": \"New York\"}"
Enter fullscreen mode Exit fullscreen mode

Mapping approach with NamedTuple

from typing import NamedTuple

class MyObjectTuple(NamedTuple):

my_obj = json.loads(my_json_str, object_hook=lambda data: MyObjectTuple(**data))

# output: MyObjectTuple(name='John', city='New York', age=31)
# output: {'name': 'John', 'city': 'New York', 'age': 31}
Enter fullscreen mode Exit fullscreen mode

Decode class without custom encoder

obj_str = json.dumps(my_obj._asdict())
# output: {"name": "John", "city": "New York", "age": 31}
Enter fullscreen mode Exit fullscreen mode

Do you any other method to object decode/encode? Do you think that it can be done better?. Leave your thoughts below, feedback is always welcomed :)

Top comments (2)

gravesli profile image

I think you are great! i just want to discuss tech with Python developer.
I built a display machine state using Python3 with Flask!
Flask State
Should i can get some improvement suggestions from you? Thanks~

gravesli profile image

That's great. Would you give me a star on GitHub Flask State?
because my project isn't active. ^.^