【问题标题】:Python: how can I catch a exception and continue?Python:如何捕获异常并继续?
【发布时间】:2011-10-18 02:52:47
【问题描述】:

为什么你有一个包含数字和其他类型对象的列表?您似乎在尝试弥补设计缺陷。

事实上,我希望它以这种方式工作,因为我想保留已经在 J​​sonedData() 中编码的数据,然后我希望 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]

【问题讨论】:

  • 你为什么不关心 TypeError?你至少不想看看哪里出了问题吗?
  • 为什么你有一个包含数字和其他类型对象的列表?您似乎在尝试弥补设计缺陷。

标签: python json exception


【解决方案1】:

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 "]"

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 嗨,事实上,我想在数据是我的类实例的地方插入原始字符串。也许 cmets 也是。所以默认和跳过键都不适合。这就是为什么我要查看例外情况...无论如何谢谢
    • @tdihp,那么默认就可以满足您的需求。你可以设置默认返回一个原始字符串。
    • 如果我默认返回一个原始字符串,它将被视为普通字符串对象,并编码为一个json字符串对象。我对吗?但是,如果我希望它是一个 json 编码的对象,真正“原始”地添加到转储输出中,那么默认情况下这可能吗?例如,我返回 '[1,2,3,4,5,"really?"] /*this is already encrypted*/' 我希望这样,而不是在任何字符串包装中
    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多