前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JSON 无法序列化

JSON 无法序列化

原创
作者头像
华科云商小徐
发布2024-06-07 13:44:25
640
发布2024-06-07 13:44:25
举报
文章被收录于专栏:小徐学爬虫小徐学爬虫

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

1、问题背景

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

2、解决方案

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

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

代码语言:javascript
复制
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() 对象提供一个默认编码函数。例如:

代码语言:javascript
复制
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 字符串。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档