Python:如何捕获异常并继续?

2 投票
2 回答
2090 浏览
提问于 2025-04-17 04:31

你为什么会有一个同时包含数字和其他类型对象的列表?听起来像是在弥补设计上的缺陷。

其实,我想这样做是因为我想保留已经用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]

2 个回答

4

tryexcept 放到循环里面,围绕着 json.JSONEncoder().encode(item) 这行代码:

print "[",
lst = [1, 2, 3, JsonedData(u'4'), 5]
for i, item in enumerate(lst):
    try:
        chunk = json.JSONEncoder().encode(item)
    except TypeError: 
        pass
    else:
        print chunk
    finally:
        # dont print the ',' if this is the last item in the lst
        if i + 1 != len(lst):
            print ","
print "]"
3

使用 JSONEncoder()skipkeys 选项,这样它就会跳过那些无法编码的项目。或者,你可以为你的 JsonedData 对象创建一个 default 方法。具体可以参考 官方文档

撰写回答