2

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]
2
  • Why aren't you concerned about the TypeError? Don't you at least want to see what's failing? Commented Oct 18, 2011 at 2:56
  • 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. Commented Oct 18, 2011 at 3:15

2 Answers 2

4

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 "]"
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

Hi, In fact, I want to insert raw string where the data is my class instance. maybe comments, too. so both default and skipkeys do not fit. that's why I'm looking at exceptions... thanks anyway
@tdihp, default would work for what you want then. you can set up default to return a raw string.
if I return a raw string in default, it will be treated as normal string object, and encode to a json string object. am I right? But if I want it to be a json-encoded object, to really 'raw'ly add to the dump output, is that possible with default? for example, I return '[1,2,3,4,5,"really?"] /*this is already encoded*/' and I want it that way, not in any string wrapping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.