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.

Author xsmyqf
Recipients xsmyqf
Date 2020-05-02.04:02:49
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1588392170.43.0.455373340888.issue40475@roundup.psfhosted.org>
In-reply-to
Content
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.
History
Date User Action Args
2020-05-02 04:02:50xsmyqfsetrecipients: + xsmyqf
2020-05-02 04:02:50xsmyqfsetmessageid: <1588392170.43.0.455373340888.issue40475@roundup.psfhosted.org>
2020-05-02 04:02:50xsmyqflinkissue40475 messages
2020-05-02 04:02:49xsmyqfcreate