Python Algorithm: create Object from JSON

As shown in the following example, you can use the @wrap (which return another wrapper) to to transfer JSON to object in the python.

This blog written conjunction with the Python Algorithm to flattening JSON 1.

from functools import wraps

def json_to_object(func):
    @wraps(func)
    def wrapper(self, d):
        for name, value in d.iteritems():
            setattr(self, name,value)
        return func(self, d)
    return wrapper


class Person(object):
    @json_to_object
    def __init__(self, d):
        pass

a = Person({'firstName':'Tom', 'lastName':'Hanks', 'age':50})

a.firstName
a.lastName
a.age

More advanced version

from functools import wraps

def json_to_object(func):
    @wraps(func)
    def wrapper(self, d):
        for name, value in d.iteritems():
            if type(value) == dict:
                print(value)
                setattr(self,name,Person.fromJson(value))
            else:
                setattr(self, name,value)
        return func(self, d)
    return wrapper


class Base(object):

    @json_to_object
    def __init__(self,d):
        pass


class Person(Base):
    @classmethod
    def fromJson(cls, json_data):
        return cls(json_data)
    

a = Person.fromJson({'name':{'firstName':'Tom', 'lastName':'Hanks'}, 'age':20})

a.__dict__
a.name.lastName
a.name.firstName

Reference

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python