【问题标题】:json serialization of a list of objects of a custom class自定义类的对象列表的json序列化
【发布时间】:2020-05-02 03:10:48
【问题描述】:

我有一个歌曲类,它保存歌曲的属性,它是一个自定义类。我还有一个名为曲目列表的列表中的歌曲列表。当我尝试 json.dump 列表时,我收到一条错误消息:

TypeError: Object of type 'Song' is not JSON serializable

我将如何将此歌曲列表转换为 json?

这是返回错误的附加相关代码:

class Song:
def __init__(self, sname, sartist, coverart, albname, albartist, spotid):
    self.sname = sname
    self.sartist = sartist
    self.coverart = coverart
    self.albname = albname
    self.albartist = albartist
    self.spotid = spotid

tracklist = createDict(tracks) ##creates the list of songs, works fine
jsontracks = json.dumps(tracklist)
pp.pprint(jsontracks)

谢谢

【问题讨论】:

标签: python json python-3.x class serialization


【解决方案1】:

我通过在类中添加一个编码方法解决了这个问题:

def encode(self):
    return self.__dict__

并向 json.dumps 添加一些参数:

jsontracks = json.dumps(tracklist, default=lambda o: o.encode(), indent=4)

这将“爬”到您的类树(如果您有任何子类)并自动将每个对象编码为 json 列表/对象。这应该适用于几乎任何类,并且输入速度很快。您可能还想控制哪些类参数被编码为:

def encode(self):
    return {'name': self.name,
            'code': self.code,
            'amount': self.amount,
            'minimum': self.minimum,
            'maximum': self.maximum}

或者编辑速度快一点(如果你像我一样懒惰的话):

def encode(self):
    encoded_items = ['name', 'code', 'batch_size', 'cost',
                     'unit', 'ingredients', 'nutrients']
    return {k: v for k, v in self.__dict__.items() if k in encoded_items}

完整代码:

import json


class Song:
    def __init__(self, sname, sartist, coverart, albname, albartist, spotid):
        self.sname = sname
        self.sartist = sartist
        self.coverart = coverart
        self.albname = albname
        self.albartist = albartist
        self.spotid = spotid

    def encode(self):
        return self.__dict__


tracklist = [
    Song('Imagine', 'John Lennon', None, None, None, None),
    Song('Hey Jude', 'The Beatles', None, None, None, None),
    Song('(I Can\'t Get No) Satisfaction', 'The Rolling Stones', None, None, None, None),
]

jsontracks = json.dumps(tracklist, default=lambda o: o.encode(), indent=4)
print(jsontracks)

输出:

[
    {
        "sname": "Imagine",
        "sartist": "John Lennon",
        "coverart": null,
        "albname": null,
        "albartist": null,
        "spotid": null
    },
    {
        "sname": "Hey Jude",
        "sartist": "The Beatles",
        "coverart": null,
        "albname": null,
        "albartist": null,
        "spotid": null
    },
    {
        "sname": "(I Can't Get No) Satisfaction",
        "sartist": "The Rolling Stones",
        "coverart": null,
        "albname": null,
        "albartist": null,
        "spotid": null
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 2014-05-19
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多