JSON 无法序列化

JSON 无法序列化通常出现在尝试将某些类型的数据转换为 JSON 字符串时,这些数据类型可能包含不可序列化的内容。 JSON 序列化器通常无法处理特定类型的数据,例如日期时间对象、自定义类实例等。在将数据转换为 JSON 字符串之前,确保所有数据都是可序列化的。我们可以编写自定义的序列化器来处理不可序列化的对象,或者将对象转换为可序列化的类型。

1、问题背景

您有一个 JSON 对象,其中包含一个 ObjectId() 对象。当您尝试使用 json.dumps() 函数序列化这个对象时,您收到了错误提示:"raise TypeError(repr(o) + " is not JSON serializable")"。

2、解决方案

要解决此问题,您可以使用两种方法:

方法一:将 ObjectId() 对象替换为基本值。例如:

python 复制代码
import json

d = {
    "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&params=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() 对象提供一个默认编码函数。例如:

python 复制代码
import json

def objectid_default(obj):
    if isinstance(obj, ObjectId):
        return str(obj)  # hex string version
    raise 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&params=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 字符串。

如有任何问题可以截图留言讨论。

相关推荐
灏瀚星空7 分钟前
基于Python的量化交易实盘部署与风险管理指南
开发语言·python
GzlAndy9 分钟前
MySQL全局优化
数据库·mysql
m0_7415747512 分钟前
mysql主从同步
数据库·mysql
Run_Teenage13 分钟前
C++类和对象:运行符重载、取地址运算符重载、const 修饰的类如何作为参数
开发语言·c++
一只小bit13 分钟前
More Effective C++:改善编程与设计(上)
开发语言·c++·方法·技巧
钢铁男儿1 小时前
C# 方法(栈帧)
开发语言·c#
小白教程1 小时前
MySQL数据库的安全性防护
数据库·mysql
Lion Long1 小时前
CodeBuddy 中国版 Cursor 实战:Redis+MySQL双引擎驱动〈王者荣耀〉战区排行榜
数据库·redis·mysql·缓存·腾讯云·codebuddy首席试玩官·codebuddy
忆源3 小时前
【Qt】之音视频编程1:QtAV的背景和安装篇
开发语言·qt·音视频
敲键盘的小夜猫3 小时前
Python核心数据类型全解析:字符串、列表、元组、字典与集合
开发语言·python