New submission from xie <xsm...@qq.com>:

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.

----------
messages: 367912
nosy: xsmyqf
priority: normal
severity: normal
status: open
title: json.JSONEncoder override default method
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue40475>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to