Requests: allow custom JSONEncoder for the request's json param

Created on 3 Sep 2015  路  5Comments  路  Source: psf/requests

Using the json param when making a request is awesome:

payload = {'blip': 'blaz'}
r = requests.get('http://foo.bar', json=payload)

Using the response property is great as well, especially since you can use a custom json decoder:

r.json(cls=MyCustomDecoder)

It would be nice to allow a param to be passed that could be applied to the dumps of the json value.

payload = {'blip': Decimal(69)}
json_params = {'cls': MyCustomEncoder}
r = requests.get('http://foo.bar', json=payload, json_params=json_params)

Most helpful comment

I think the better way is to manually use it yourself:

r = requests.post('http://foo.bar', data=json.dumps(some_data, cls=CustomJSONEncoder), headers={'Content-Type': 'application/json'})

All 5 comments

I think this is interesting, but generally requests is very averse to adding new keyword arguments to requests.*. I don't think it's valuable enough to justify adding the new argument, I'm afraid. Sorry!

Is there a better way to always use a custom json encoder? This way is brittle and gross and does not even work with stuff in master (fine for 2.7.0).

import json
import functools
from decimal import Decimal

import requests


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return round(float(obj), 2)
        return json.JSONEncoder.default(self, obj)

# yuck
requests.models.json_dumps = functools.partial(json.dumps, cls=CustomJSONEncoder)

r = requests.post('http://foo.bar', json={'foo': Decimal(69)})

I think the better way is to manually use it yourself:

r = requests.post('http://foo.bar', data=json.dumps(some_data, cls=CustomJSONEncoder), headers={'Content-Type': 'application/json'})

Yep, I am already doing it that way. Was wanting a way to globally have it use a specific encoder/decoder when messing with json

@drmaples then make a function that handles that "globally" for yourself. We won't be introducing this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

avinassh picture avinassh  路  4Comments

brainwane picture brainwane  路  3Comments

xsren picture xsren  路  3Comments

mitar picture mitar  路  4Comments

NoahCardoza picture NoahCardoza  路  4Comments