Python:如何捕获异常并继续?
为什么你有一个包含数字和其他类型对象的列表?看起来您正在尝试弥补设计缺陷。
事实上,我希望它以这种方式工作,因为我想保留已经在 JsonedData() 中编码的数据,然后我希望 json 模块给我一些方法来插入“原始”项目数据而不是默认值,以便编码的 JsonedData 可以重用。
这是代码,谢谢
import json
import io
class JsonedData():
def __init__(self, data):
self.data = data
def main():
try:
for chunk in json.JSONEncoder().iterencode([1,2,3,JsonedData(u'4'),5]):
print chunk
except TypeError: pass# except come method to make the print continue
# so that printed data is something like:
# [1
# ,2
# ,3
# ,
# ,5]
Why do you have a list of both numbers and some other kind of object? It seems like you're trying to compensate for a design flaw.
As a matter of fact, I want it work this way because I want to keep data that is already encoded in JsonedData(), then I want json module to give me some way to insert a 'raw' item data rather than the defaults, so that encoded JsonedData could be reuseable.
here's the code, thanks
import json
import io
class JsonedData():
def __init__(self, data):
self.data = data
def main():
try:
for chunk in json.JSONEncoder().iterencode([1,2,3,JsonedData(u'4'),5]):
print chunk
except TypeError: pass# except come method to make the print continue
# so that printed data is something like:
# [1
# ,2
# ,3
# ,
# ,5]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
try
/except
放在json.JSONEncoder().encode(item)
周围的循环中:put the
try
/except
inside the loop around thejson.JSONEncoder().encode(item)
:使用
JSONEncoder()
的skipkeys
选项,以便它跳过无法编码的项目。或者,为您的JsonedData
对象创建一个default
方法。请参阅文档。Use the
skipkeys
option forJSONEncoder()
so that it skips items that it can't encode. Alternatively, create adefault
method for yourJsonedData
object. See the docs.