Ani*_*dha 0 python serialization json class python-3.x
I have a song class, which holds the attributes to a song, and it is a custom class. I also have a list of songs in a list called track list. When I try to json.dump the list, I get an error that says :
TypeError: Object of type 'Song' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
How would I go about converting this list of songs to json?
Here is the additional relevant code that returns the error:
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)
Run Code Online (Sandbox Code Playgroud)
Thanks
小智 5
我通过向类添加一个 encode 方法解决了这个问题:
def encode(self):
return self.__dict__
Run Code Online (Sandbox Code Playgroud)
并向 json.dumps 添加一些参数:
jsontracks = json.dumps(tracklist, default=lambda o: o.encode(), indent=4)
Run Code Online (Sandbox Code Playgroud)
这将“爬行”您的类树(如果您有任何子类)并自动将每个对象编码为 json 列表/对象。这应该适用于几乎任何类并且可以快速输入。您可能还想控制哪些类参数使用以下内容进行编码:
def encode(self):
return {'name': self.name,
'code': self.code,
'amount': self.amount,
'minimum': self.minimum,
'maximum': self.maximum}
Run Code Online (Sandbox Code Playgroud)
或者编辑得更快一点(如果你像我一样懒惰):
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}
Run Code Online (Sandbox Code Playgroud)
完整代码:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
[
{
"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
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |