当前位置: 首页>前端>正文

JSON 无法序列化

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

1、问题背景

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

2、解决方案

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

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

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

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


https://www.xamrdz.com/web/2b41964388.html

相关文章: