How to generate a Python object from JSON

json – JavaScript Object Notation Serializer -Python Module of the Week Is a sutra copy of

Please refer to How to create a Perl object from JSON -Qiita for some explanation.

class MyObj(object):
    def __init__(self, s, y):
        self.s = s
        self.y = y

    def __repr__(self):
        return '<MyObj(%s)>' % self.s


def main():
    import json

    obj = MyObj('instance value goes here', "a")
    print(obj)

    # print('First attempt')
    try:
        print(json.dumps(obj))
    except TypeError, err:
        print("ERROR:", err)

    def convert_to_builtin_type(obj):
        # print('default(', repr(obj), ')')
        # Convert objects to a dictionary of their representation
        d = {'__class__': obj.__class__.__name__,
             '__module__': obj.__module__,
             }
        d.update(obj.__dict__)
        return d

    def dict_to_object(d):
        if '__class__' in d:
            class_name = d.pop('__class__')
            module_name = d.pop('__module__')
            module = __import__(module_name)
            # print('MODULE:', module)
            class_ = getattr(module, class_name)
            # print('CLASS:', class_)
            args = dict((key.encode('ascii'), value) for key, value in d.items())
            # print('INSTANCE ARGS:', args)
            inst = class_(**args)
        else:
            inst = d
        return inst

    # print('With default')

    json_txt = json.dumps(obj, default=convert_to_builtin_type)
    print(json_txt)

    obj2 = json.loads(json_txt, object_hook=dict_to_object)
    print(obj2)
    print(obj2.s)


if __name__ == '__main__':
    main()
    exit(0)

"""
<MyObj(instance value goes here)>
ERROR: <MyObj(instance value goes here)> is not JSON serializable
{"y": "a", "s": "instance value goes here", "__module__": "__main__", "__class__": "MyObj"}
<MyObj(instance value goes here)>
instance value goes here
"""

Recommended Posts

How to generate a Python object from JSON
How to open a web browser from python
How to create a function object from a string
How to create a JSON file in Python
Python script to create a JSON file from a CSV file
[Python] How to call a c function from python (ctypes)
How to create a kubernetes pod from python code
How to write a Python class
Touch a Python object from Elixir
[Introduction to Python] How to parse JSON
How to access wikipedia from python
How to run a Python program from within a shell script
How to launch AWS Batch from a python client app
How to generate a public key from an SSH private key
Script to generate directory from json file
[Python] How to make a class iterable
How to update Google Sheets from Python
Send a message from Python to Slack
Create a JSON object mapper in Python
[Python] How to invert a character string
How to get a stacktrace in python
How to access RDS from Lambda (python)
Generate a class from a string in Python
How to create a repository from media
How to run a Maya Python script
How to get a string from a command line argument in python
[Python] How to get & change rows / columns / values from a table.
How to remove duplicates from a Python list while preserving order.
Send a message from Slack to a Python server
How to generate a new loggroup in CloudWatch using python within Lambda
Edit Excel from Python to create a PivotTable
How to read a CSV file with Python 2/3
How to create a Python virtual environment (venv)
How to clear tuples in a list (Python)
How to install Python
How to generate permutations in Python and C ++
How to embed a variable in a python string
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Study from Python Hour7: How to use classes
How to install python
How to read JSON
How to get a value from a parameter store in lambda (using python)
[Introduction to Python] How to handle JSON format data
How to add a Python module search path
How to handle Linux commands well from Python
How to extract coefficients from a fractional formula
How to notify a Discord channel in Python
Create a datetime object from a string in Python (Python 3.3)
[Python] How to draw a histogram in Matplotlib
Generate and output plantuml object diagram from Python object
[Cloudian # 10] Try to generate a signed URL for object publishing in Python (boto3)
I made a tool to generate Markdown from the exported Scrapbox JSON file
[Python] How to easily drop a child process started by multiprocess from another process
[Python] How to remove duplicate values from the list
Parse a JSON string written to a file in Python
How to convert / restore a string with [] in python
[Python] How to draw a line graph with Matplotlib
How to set up a Python environment using pyenv
I want to generate a UUID quickly (memorandum) ~ Python ~
How to scrape image data from flickr with python