alortimor alortimor - 3 months ago 25
JSON Question

json encoding issue in Python

I am attempting a custom encode, but get an error. The following code sample generates an error:

#!/usr/bin/python3

import json

class Contact:
def __init__(self, first, last):
self.first = first
self.last = last

@property
def full_name(self):
return ("{} {}".format(self.first, self.last))

class ContactEncoder(json.JSONEncoder):
def defualt(self, obj):
if isinstance(obj, Contact):
return {"is_contact": 'T'
,"first": obj.first
,"last": obj.last
,"full_name": obj.full_name}
return super().defualt(obj)

if __name__ == "__main__":
c = Contact("Jay", "Loophole")
print(json.dumps(c.__dict__))
print(json.dumps(c, cls=ContactEncoder))


The error generated is:

{"first": "Jay", "last": "Loophole"}
Traceback (most recent call last):
File "json_dump.py", line 26, in <module>
print(json.dumps(c, cls=ContactEncoder))
File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <__main__.Contact object at 0x7ffb3445a400> is not JSON serializable


The default dictionary is successfully displayed, but when a custom encode is passed as a cls parameter, an error occurs.
Any suggestions for the reason for the error?

Answer

Here is your updated code after the defUAlt --> defAUlt correction:

import json

class Contact:
  def __init__(self, first, last):
    self.first = first
    self.last = last

  @property
  def full_name(self):
    return ("{} {}".format(self.first, self.last))

class ContactEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, Contact):
      return  {"is_contact": 'T'
              ,"first": obj.first
              ,"last": obj.last
              ,"full_name": obj.full_name}
    return super().default(obj)

if __name__ == "__main__":
  c = Contact("Jay", "Loophole")
  print(json.dumps(c.__dict__))
  print(json.dumps(c, cls=ContactEncoder))

You can check it out live on this page.