Message367912
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. |
|
Date |
User |
Action |
Args |
2020-05-02 04:02:50 | xsmyqf | set | recipients:
+ xsmyqf |
2020-05-02 04:02:50 | xsmyqf | set | messageid: <1588392170.43.0.455373340888.issue40475@roundup.psfhosted.org> |
2020-05-02 04:02:50 | xsmyqf | link | issue40475 messages |
2020-05-02 04:02:49 | xsmyqf | create | |
|