欧美性猛交xxx嘿人猛交_又色又爽又高潮免费观看_精品国产一区二区三区久久影院_青娱乐极品视觉盛宴国产视频

技術頻道導航
HTML/CSS
.NET技術
IIS技術
PHP技術
Js/JQuery
Photoshop
Fireworks
服務器技術
操作系統
網站運營

贊助商

分類目錄

贊助商

最新文章

搜索

【解決】Python將JSON寫入文件:Object of type Your Class is not JSON serializable

作者:admin    時間:2022-1-12 11:3:55    瀏覽:

Python的內置 json 模塊只能處理具有直接 JSON 等價物的Python 基元類型(例如,str、int、float、bool、None等)。

如果 Python 字典包含一個自定義 Python 對象作為鍵之一,并且如果我們嘗試將其轉換為 JSON 格式,你將得到一個 TypeError 即Object of type "Your Class" is not JSON serializable.

 Python將JSON寫入文件

如果 JSON 數據中不需要此自定義對象,你可以使用json.dump()方法的skipkeys=true參數跳過它。

如果skipkeys=true為 True,則將dict跳過非基本類型(str、int、float、bool、None)的鍵,而不是引發 TypeError。

如果需要轉成 JSON,那么可以參考文章如何使 Python 類 JSON 可序列化。

現在,讓我們看看這個例子。

import json

class PersonalInfo:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def showInfo(self):
        print("Developer name is " + self.name, "Age is ", self.age)

dev = PersonalInfo("John", 36)
developer_Dict = {
    PersonalInfo: dev,
    "salary": 9000,
    "skills": ["Python", "Machine Learning", "Web Development"],
    "email": "admin@webkaka.com"
}
print("Writing JSON data into file by skipping non-basic types")
with open("developer.json", "w") as write_file:
    json.dump(developer_Dict, write_file, skipkeys=True)
print("Done")

輸出:

Writing JSON data into file by skipping non-basic types
Done

文件內容:

 
跳過基本類型后的 JSON 文件(點擊圖片放大)

在 JSON 輸出中看到,該PersonalInfo對象被跳過。

您可能對以下文章也感興趣

標簽: Python  
x