tdihp
tdihp

Reputation: 2389

Python: how can I catch a exception and continue?

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]

Upvotes: 2

Views: 2097

Answers (2)

chown
chown

Reputation: 52748

put the try/except inside the loop around the 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 "]"

Upvotes: 4

imm
imm

Reputation: 5919

Use the skipkeys option for JSONEncoder() so that it skips items that it can't encode. Alternatively, create a default method for your JsonedData object. See the docs.

Upvotes: 3

Related Questions