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

时间:2011-10-18 02:52:47

标签: python json exception

  

为什么你有一个数字列表和一些其他类型的对象?看起来你正试图弥补设计缺陷。

事实上,我希望它以这种方式工作,因为我想保留已经在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 个答案:

答案 0 :(得分:4)

try / except放在围绕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 "]"

答案 1 :(得分:3)

skipkeys使用JSONEncoder()选项,以便跳过无法编码的项目。或者,为default对象创建JsonedData方法。请参阅the docs