This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: json.JSONEncoder override default method
Type: behavior Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, rhettinger, xsmyqf, xtreak
Priority: normal Keywords:

Created on 2020-05-02 04:02 by xsmyqf, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg367912 - (view) Author: xie (xsmyqf) Date: 2020-05-02 04:02
I see an example from here:https://docs.python.org/3/library/json.html
------It is about custom method from python object to json string:-----

import json
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        print("hi")
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

s2=json.dumps(2 + 1j, cls=ComplexEncoder)
print(s2)

-------I wrote an program like it,but not the result I want:-------
class MyEncoder(json.JSONEncoder):
    def default(self,obj):
        print("hi")
        if isinstance(obj,dict):
            print("it is dict!")
            return obj["name"]
        return json.JSONEncoder.default(self,obj)

print(MyEncoder().encode({"name":"sun","age":40}))
jsonStr=json.dumps({"name":"wang","age":30},cls=MyEncoder)
print(jsonStr)

--------the result of the program is:---------
{"name": "sun", "age": 40}
{"name": "wang", "age": 30}

--------I think it should be:---------
sun
wang

what I missed?I am very confused.
msg367915 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2020-05-02 04:56
https://docs.python.org/3/library/json.html#json.JSONEncoder

> To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

default is called only when the object cannot be serialized by default. In this case dict is serializable and default won't be called.
msg367918 - (view) Author: xie (xsmyqf) Date: 2020-05-02 06:45
I got it,Thank you!
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84655
2020-05-02 06:45:51xsmyqfsetstatus: open -> closed
resolution: fixed
messages: + msg367918

stage: resolved
2020-05-02 04:56:33xtreaksetnosy: + rhettinger, ezio.melotti, xtreak
messages: + msg367915
2020-05-02 04:02:50xsmyqfcreate