我需要序列化一個包含原始 python 數(shù)據(jù)類型的元組,或者換句話說,一個內(nèi)置類,例如。整數(shù)/字符串。但是 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條經(jīng)驗 獲得超4個贊
無法將 JSON 或 Python 序列化為type
JSON 值。如RFC7159 第 3 節(jié)所述,唯一可用的值是:
假/空/真/對象/數(shù)組/數(shù)字/字符串
但是,您可以將 Python 序列化為type
JSON 字符串。例如,Pythonint
會變成 JSON 字符串值"int"
。
由于 Python 關鍵字int
是類型的對象type
。您可以使用__name__
它來獲取其字符串名稱。例如:print(int.__name__)
。
為了自動編碼,我讓你檢查這個使用自定義的答案JSONEncoder
。
添加回答
舉報
0/150
提交
取消