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 字符串。

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

相关推荐
猪猪虾的业余生活几秒前
Qt 驾校考试系统项目实现
开发语言·qt
香菇滑稽之谈2 分钟前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式
补三补四10 分钟前
Yashan DB 实例管理
数据库·oracle
风莫寻24 分钟前
【Troubleshot】Qt 长按按键 keyPressEvent keyReleaseEvent 自动重复问题
开发语言·qt
ZC·Shou24 分钟前
Rust 之一 基本环境搭建、各组件工具的文档、源码、配置
开发语言·rust·cargo·rustc·rustup·clippy·rustfmt
Hello.Reader25 分钟前
深入理解 Rust 中的模式匹配语法
开发语言·rust
最胖的小仙女30 分钟前
通过动态获取后端数据判断输入的值打小
开发语言·前端·javascript
yqcoder34 分钟前
Express + MongoDB + multer 解决文件上传 originalname 中文乱码
数据库·mongodb·express
阿波拉35 分钟前
AttributeError: module ‘backend_interagg‘ has no attribute ‘FigureCanvas’问题解决
开发语言·python
l_tian_tian_1 小时前
JavaWeb——Mybatis、JDBC、数据库连接池、lombok
java·数据库·mybatis