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.
事实上,我希望它以这种方式工作,因为我想保留已经在 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]
最佳答案
将 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 "]"
关于Python:如何捕获异常并继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801903/