Requests: ujson option

Created on 12 Sep 2013  路  8Comments  路  Source: psf/requests

Hi,

Is it possible to use ujson as an optional JSON encoder/decoder for requests? Or, if ujson satisfies all the use cases of requests, replace simplejson with ujson?

Most helpful comment

For those finding this issue circa-2019, please not that I believe the current way of doing this would instead be:

import requests
import ujson

requests.models.complexjson = ujson

I've seen plenty of examples of code on Github that monkey-patches requests.models.json, which does not appear to accomplish the stated goal, since that attribute of models does not exist and is not used in the modern requests code base.

All 8 comments

You absolutely can. The easiest way to do it is to monkeypatch:

import requests
import ujson

requests.models.json = ujson

That _should_ cause all further calls to Response.json() to use ujson. As that's the only place in Requests that uses simplejson, that should cover everything.

So by looking at Response.json(), I reckon it's safe to use ujson as default for requests?

Certainly it will be safe to override that behaviour. For obvious reasons we won't change this in the core library, but I highly encourage you to use ujson if it suits your purpose better. =)

Fair :)

Thank you @Lukasa !

My pleasure, I hope you enjoy using Requests! =D Let us know if you have any problems. :star:

@Lukasa - would you consider using ujson by default if it is installed?

Something like:

``` python:

in compat.py

try:
import ujson as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
```

Nope. =)

I see no reason for Requests to favour ujson over any other third-party JSON decoder. We do nothing very complicated with JSON decoding, so replacing the decoder we use either via monkeypatching or via doing the decoding yourself is totally safe. With that in mind, there's no good reason to move away from the standard library in Requests proper.

For those finding this issue circa-2019, please not that I believe the current way of doing this would instead be:

import requests
import ujson

requests.models.complexjson = ujson

I've seen plenty of examples of code on Github that monkey-patches requests.models.json, which does not appear to accomplish the stated goal, since that attribute of models does not exist and is not used in the modern requests code base.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jake491 picture jake491  路  3Comments

justlurking picture justlurking  路  3Comments

JimHokanson picture JimHokanson  路  3Comments

remram44 picture remram44  路  4Comments

ReimarBauer picture ReimarBauer  路  4Comments