0

I'm using json.dump with a custom encoder in python2, and I want to pass an additional parameter to the encoder, this way:

json.dump(data, fp, type, cls=MyEncoder)

Following How to pass parameters to a custom JSONEncoder default() function in Python I wrote the encoder:

class MyEncoder(json.JSONEncoder):
    def __init__(self, type, **kwargs):
        super(MyEncoder, self).__init__(**kwargs)
        self.type = type

    def default(self, obj):
        type = self.type
        if isinstance(obj, datetime):
            # there was the line:

but, in init, the type value is assigned to kwargs['skipkeys'], not to type variable.

What am I missing?

Would it be different in python3?

1 Answer 1

1

According to the documentation, the third argument to json.dumps is the skipkeys argument, and so that's what the type argument in json.dump(data, fp, type, cls=MyEncoder) is treated as; the fact that the variable is named type is irrelevant, as json.dumps never sees that name. In order to make json.dumps see that name, you have to pass type as a keyword argument: json.dump(data, fp, type=type, cls=MyEncoder).

Sign up to request clarification or add additional context in comments.

1 Comment

@PaoloBenvenuto: Yes, it should.

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.