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

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

相关推荐
day3ZY11 分钟前
清理C盘缓存,电脑缓存清理怎么一键删除,操作简单的教程
c语言·开发语言·缓存
学地理的小胖砸23 分钟前
【高分系列卫星简介】
开发语言·数码相机·算法·遥感·地理信息
码农豆豆25 分钟前
4.C++中程序中的命名空间
开发语言·c++
怀九日28 分钟前
C++(学习)2024.9.19
开发语言·c++·学习·重构·对象·
小纯洁w33 分钟前
MySQL 中优化 SQL 语句以提高查询性能
数据库·sql·mysql
xiaomiphone934 分钟前
【PostgreSQL教程】PostgreSQL详细介绍
数据库·sql·mysql·postgresql·oracle
Iam傅红雪38 分钟前
mysql表逆向实体类
数据库·mysql·adb
KookeeyLena842 分钟前
如何限制任何爬虫爬取网站的图片
开发语言·c++·爬虫
佘小麦1 小时前
【HTML元素居中】元素水平垂直居中的常用方法
css·html·css3
yanyanwenmeng1 小时前
matlab基础
开发语言·算法·matlab