JSON 無法序列化通常出現在嘗試將某些類型的數據轉換為 JSON 字符串時,這些數據類型可能包含不可序列化的內容。 JSON 序列化器通常無法處理特定類型的數據,例如日期時間對象、自定義類實例等。在將數據轉換為 JSON 字符串之前,確保所有數據都是可序列化的。我們可以編寫自定義的序列化器來處理不可序列化的對象,或者將對象轉換為可序列化的類型。
1、問題背景
您有一個 JSON 對象,其中包含一個 ObjectId() 對象。當您嘗試使用 json.dumps() 函數序列化這個對象時,您收到了錯誤提示:“raise TypeError(repr(o) + " is not JSON serializable")”。
2、解決方案
要解決此問題,您可以使用兩種方法:
方法一:將 ObjectId() 對象替換為基本值。例如:
import jsond = {"objectid": "427912","fooditems": "Cold Truck: Hamburger: cheeseburgers: hot dogs: hot sandwiches: cold sandwiches: egg muffins: cup of noodles: corn dogs: canned soup: coffee: hot cocoa: hot tea: gatorade: juice: milk: soda: water: fruits: fruit salad: rice pudding: yogurt: candy bars: chips: cookies: donuts: granola bars: muffins","facilitytype": "Truck","priorpermit": "1","location": {"latitude": "37.730906164188","needs_recoding": False,"longitude": "-122.373302577475"},"lot": "008","cnn": "7253000","status": "APPROVED","schedule": "http://bsm.sfdpw.org/PermitsTracker/reports/report.aspx?title=schedule&report=rptSchedule¶ms=permit=13MFF-0072&ExportPDF=1&Filename=13MFF-0072_schedule.pdf","locationdescription": "INNES AVE: EARL ST to ARELIOUS WALKER DR (700 - 799)","latitude": "37.7309061503597","blocklot": "4644008","address": "Assessors Block 4644/Lot008","approved": "2013-04-04T08:44:08","received": "Mar 15 2013 10:24AM","applicant": "Park's Catering","longitude": "-122.373302577485","expirationdate": "2014-03-15T00:00:00","permit": "13MFF-0072","y": "2094023.408","x": "6019956.89","block": "4644"
}# 將 ObjectId() 對象替換為字符串
d["_id"] = str(d["_id"])# 序列化 JSON 對象
json_string = json.dumps(d)print(json_string)
方法二:為 ObjectId() 對象提供一個默認編碼函數。例如:
import jsondef objectid_default(obj):if isinstance(obj, ObjectId):return str(obj) # hex string versionraise TypeError(obj)d = {"objectid": ObjectId("52afeb27e8de3f3174110041"),"fooditems": "Cold Truck: Hamburger: cheeseburgers: hot dogs: hot sandwiches: cold sandwiches: egg muffins: cup of noodles: corn dogs: canned soup: coffee: hot cocoa: hot tea: gatorade: juice: milk: soda: water: fruits: fruit salad: rice pudding: yogurt: candy bars: chips: cookies: donuts: granola bars: muffins","facilitytype": "Truck","priorpermit": "1","location": {"latitude": "37.730906164188","needs_recoding": False,"longitude": "-122.373302577475"},"lot": "008","cnn": "7253000","status": "APPROVED","schedule": "http://bsm.sfdpw.org/PermitsTracker/reports/report.aspx?title=schedule&report=rptSchedule¶ms=permit=13MFF-0072&ExportPDF=1&Filename=13MFF-0072_schedule.pdf","locationdescription": "INNES AVE: EARL ST to ARELIOUS WALKER DR (700 - 799)","latitude": "37.7309061503597","blocklot": "4644008","address": "Assessors Block 4644/Lot008","approved": "2013-04-04T08:44:08","received": "Mar 15 2013 10:24AM","applicant": "Park's Catering","longitude": "-122.373302577485","expirationdate": "2014-03-15T00:00:00","permit": "13MFF-0072","y": "2094023.408","x": "6019956.89","block": "4644"
}# 使用默認編碼函數序列化 JSON 對象
json_string = json.dumps(d, default=objectid_default)print(json_string)
通過理解上述問題并采取相應的解決方法,相信我們能更好的解決 JSON 無法序列化的問題,并成功將數據轉換為 JSON 字符串。
如有任何問題可以截圖留言討論。