Python - JSON string to Python object

If you are learning Python and want to know how to convert JSON string into Python object, here are some examples using regular json library. This will save you a few hours of research. I researched around and collected a lot of options that use the regular json library.

My choice is the function try4() below.

#!/usr/bin/python
import json
from collections import namedtuple

########################################################################################

class User(object):
    def __init__(self, name, username):
        self.name = name
        self.username = username


def object_decoder(obj):
    if '__type__' in obj and obj['__type__'] == 'User':
        return User(obj['name'], obj['username'])
    return obj


def try1():
    print "--------try 1----------"
    myobj = json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}', object_hook=object_decoder)
    print type(User)
    print myobj.name
    print myobj.username

    #If you want to access data in a dictionary via the json module do this
    user = json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}')
    print user['name']
    print user['username']
    print json.dumps(user)

########################################################################################

class Hometown(object):
    def __init__(self, name, id):
        self.name = name
        self.id = id


class Customer(object):
    def __init__(self, name, hometown_name, hometown_id):
        _hometown = Hometown(hometown_name, hometown_id)
        self.name = name
        self.hometown = _hometown


def print_object():
    print "-------------------"
    mycustomer = Customer("Jane Do", "Chicago", "456")
    print mycustomer.hometown.id


########################################################################################

def _json_object_hook(d):
    return namedtuple('X', d.keys())(*d.values())


def json2obj(data):
    return json.loads(data, object_hook=_json_object_hook)


def try2():
    print "--------try 2----------"
    data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
    # Parse JSON into an object with attributes corresponding to dict keys.
    myuser = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
    print myuser.name, myuser.hometown.name, myuser.hometown.id

    # Convert JSON string to object
    myuser2 = json2obj(data)
    print myuser2.name, myuser2.hometown.name, myuser2.hometown.id

    # Convert object back to JSON string
    print json.dumps(myuser)
    print json.dumps(myuser2, sort_keys=True)


########################################################################################

class MyUser(object):
    def __init__(self, name, username):
        self.name = name
        self.username = username


def try3():
    print "-------try 3------------"
    your_json = '{"name": "John Smith", "username": "jsmith"}'
    myuser_obj = json.loads(your_json)
    myuser_theobject = MyUser(**myuser_obj)
    print myuser_theobject.name, myuser_theobject.username
    print json.dumps(myuser_theobject.__dict__)


########################################################################################

class MyHometown(object):
    def __init__(self, name, id):
        self.name = name
        self.id = id


class MyCustomer(object):
    #def __init__(self, name, hometown_name, hometown_id):    #    _hometown = MyHometown(hometown_name, hometown_id)    #    self.name = name    #    self.hometown = _hometown

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


def jdefault(o):
    if isinstance(o, set):
        return list(o)
    return o.__dict__

def try4():
    print "-------try 4------------"
    your_json = '{"name": "Almir Smith", "hometown": {"name": "Irvine", "id": 567}}'
    mycustomer_obj = json.loads(your_json)  #dictionary    print mycustomer_obj
    print json.dumps(mycustomer_obj)

    # convert it into the real object
    mycustomer_theobject = MyCustomer(**mycustomer_obj)
    mycustomer_theobject.hometown = MyHometown(**mycustomer_theobject.hometown)
    print mycustomer_theobject.name, mycustomer_theobject.hometown.name, mycustomer_theobject.hometown.id

    # Convert the object back to JSON string
    print json.dumps(mycustomer_theobject, default=jdefault)
    #mycustomer_theobject.hometown = mycustomer_theobject.hometown.__dict__
    #print json.dumps(mycustomer_theobject.__dict__)

    # Create an instance of MyCustomer object and then convert it into JSON string
    the_hometown = MyHometown('Costa Mesa', 9348)
    the_customer = MyCustomer('Almir', the_hometown)
    print json.dumps(the_customer, default=jdefault)


########################################################################################

########################################################################################

def _myjson_object_hook(d):
    return namedtuple('X', d.keys())(*d.values())


def myjson2obj(data):
    return json.loads(data, object_hook=_myjson_object_hook)


def try5():
    print "--------try 5----------"
    data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

    # Parse JSON into an object with attributes corresponding to dict keys.
    myuser = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
    print myuser.name, myuser.hometown.name, myuser.hometown.id

    # Convert JSON string to object
    myuser2 = myjson2obj(data)
    print myuser2.name, myuser2.hometown.name, myuser2.hometown.id

    # Convert object back to JSON string    # print json.dumps(myuser)    # print json.dumps(myuser2)
    # Convert object back to named JSON string
    print json.dumps(myuser2.__dict__)


########################################################################################

def main():
    try1()
    try2()
    try3()
    try4() # It is an okay approach but it requires a bit more understanding about the nesting of your objects
    try5()


if __name__ == "__main__": main()



almirsCorner.com

#Python #JSON #PythonObject #Serialize #Deserialize 

#python #programming #code #coding #software #softwaredeveloper #softwareengineering #programmer


No comments:

Post a Comment