我需要序列化一个包含原始 python 数据类型的元组,或者换句话说,一个内置类,例如。整数/字符串。但是 json 库会抛出一个错误,例如TypeError: Object of type type is not JSON serializable完整追溯:Traceback (most recent call last):  File "C:\Users\ns877v\git\analytics-kronos-worker\useful_snippets\2.py", line 2, in <module>    json.dumps(int)  File "C:\Users\ns877v\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 231, in dumps    return _default_encoder.encode(obj)  File "C:\Users\ns877v\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 199, in encode    chunks = self.iterencode(o, _one_shot=True)  File "C:\Users\ns877v\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 257, in iterencode    return _iterencode(o, 0)  File "C:\Users\ns877v\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default    raise TypeError(f'Object of type {o.__class__.__name__} 'TypeError: Object of type type is not JSON serializable[Finished in 0.4s]运行这个来复制:import jsonjson.dumps(int)
                    
                    
                1 回答
 
                    
                    
                            明月笑刀无情
                            
                                
                            
                        
                        
                                                
                    TA贡献1828条经验 获得超4个赞
无法将 JSON 或 Python 序列化为typeJSON 值。如RFC7159 第 3 节所述,唯一可用的值是:
假/空/真/对象/数组/数字/字符串
但是,您可以将 Python 序列化为typeJSON 字符串。例如,Pythonint会变成 JSON 字符串值"int"。
由于 Python 关键字int是类型的对象type。您可以使用__name__它来获取其字符串名称。例如:print(int.__name__)。
为了自动编码,我让你检查这个使用自定义的答案JSONEncoder。
添加回答
举报
0/150
	提交
		取消
	