Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a class JSON serializable

How to make a Python class serializable?

A simple class:

class FileItem:     def __init__(self, fname):         self.fname = fname 

What should I do to be able to get output of:

>>> import json  >>> my_file = FileItem('/foo/bar') >>> json.dumps(my_file) TypeError: Object of type 'FileItem' is not JSON serializable 

Without the error

like image 758
Sergey Avatar asked Sep 22 '10 11:09

Sergey


People also ask

Why is my object not JSON serializable?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

Is JSON serializable Python?

Serialization is the process of encoding the from naive data type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null.


1 Answers

Here is a simple solution for a simple feature:

.toJSON() Method

Instead of a JSON serializable class, implement a serializer method:

import json  class Object:     def toJSON(self):         return json.dumps(self, default=lambda o: o.__dict__,              sort_keys=True, indent=4) 

So you just call it to serialize:

me = Object() me.name = "Onur" me.age = 35 me.dog = Object() me.dog.name = "Apollo"  print(me.toJSON()) 

will output:

{     "age": 35,     "dog": {         "name": "Apollo"     },     "name": "Onur" } 
like image 63
Onur Yıldırım Avatar answered Sep 19 '22 08:09

Onur Yıldırım