How To Resolve The TypeError: Object Of Type Method Is Not JSON Serializable In Python

TypeError: Object of type method is not JSON serializable

To fix the TypeError: Object of type method is not JSON serializable in Python, you can make method calls and use the JSONEncoder class. Please read the following article for details.

What causes the TypeError: Object of type method is not JSON serializable?

Method is the component responsible for handling class data in Python. There are 3 types of methods:

  • Instance method
  • Class methods
  • Static methods

Performing operations such as decoding, encoding Json from objects, you first need to import the json library. The following Python objects are supported to convert to json such as dict, list, None, False, True, Float, unicode, int, long.

Json serialization means getting Python data converted into Json string. You can do this through the json.dumps function.

The error happens because you serialize a method to a json object.

Example: 

import json

class Information: 
  # Constructor with 2 parameters and return
  def __init__(self, Information_name, Information_age):
    self.name = Information_name
    self.age = Information_age
   
  def myInfo(self):
    print(self.name,self.age)

result = Information('John','18 years old')
jsonStr = json.dumps({'information': result.myInfo}) 

Output:

TypeError: Object of type method is not JSON serializable

In the above example I use the instance method to print a Python string. Then use json.dumps() function to convert Python string to json object but get error like above.

How to solve this error?

Call method

Example:

  • The problem with the TypeError: Object of type method is not JSON serializable is that you forgot to call the method. To fix this, simply add a () to the ‘myInfo’ method.
import json

class Information:
  # Constructor with 2 parameters and return
  def __init__(self, Information_name, Information_age):
    self.name = Information_name
    self.age = Information_age
   
  def myInfo(self):
    print(self.name,self.age)

result = Information('John','18 years old')

# Perform call method
jsonStr = json.dumps({'information': result.myInfo()}) 

Output:

John 18 years old

Use the JSONEncoder class

Example:

  • I still use the instance method in this example.
  • The JSONEncoder class is used to serialize any Python object when encoding. Including encode(o). encode(o) is similar to json.dumps it will return a json string from Python data structures.
import json

from json import JSONEncoder

class Information:
    def __init__(self, Information_name, Information_age):
       	self.name = Information_name
      	self.age = Information_age

class Encoder(json.JSONEncoder):
    def default(self, i):    
            return i.__dict__

result = Information('John', '18 years old')
myJson = json.dumps(result, cls=Encoder)
print('Json serialized object:', myJson)

Output:

Json serialized object: {"name": "John", "age": "18 years old"}

Use the jsonpickle module.

The jsonpickle module takes most of the Python objects and converts them to Json and vice versa. To be able to convert Python objects into Json, I use jsonpickle.encode function.

Example:

  • Import the jsonpickle module.
  • Create instance method.
  • Using the jsonpickle .encode function converts the Python object to Json.
import jsonpickle

class Information:
    def __init__(self, Information_name, Information_age):
       	self.name = Information_name
      	self.age = Information_age

result = Information('John', '18 years old')

# Use the jsonpickle.encode function converts the Python object to Json
myJson = jsonpickle.encode(result)
print(myJson)

Output:

{"py/object": "__main__.Information", "py/state": {"name": "John", "age": "18 years old"}}

Summary

The TypeError: Object of type method is not JSON serializable is quite tricky, but we can fix it. Method 1 is so easy for you. If there is another way, let us know in the comments below. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *