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]
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 "]"
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.