[Fixed]-Django Test Client squishes nested JSON


The following works for me (using named args):

geojson = {
        "type": "Point",
        "coordinates": [1, 2]

    response = self.client.post('/validate', data=json.dumps(geojson),


Your problem indicates Django is interpreting your request as multipart/form-data rather than application/json. Try

c.post("URL", "{JSON_CONTENT}", content_type="application/json").

Another thing to watch is that Python represents dictionary keys/values using single quotes when rendered as strings, which the simplejson parser doesn’t like. Keep your hard-coded JSON objects as single-quoted strings, using double quotes inside to get around this…


My solution is the following:

In the test method:

data_dict = {'phoneNumber': user.get_profile().phone_number,
             'pinNumber': user.get_profile().pin,
                 {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067',
                  'deviceType': 'I'}})

self.client.post('/url/', data={'data': json.dumps(data_dict)})

In the view:


This sends post[‘data’] as a string. The in the view one must load the json from that string.




I’ve found that json.dumps doesn’t address the issue in many cases. Rather, I use it more selectively as such:

data = {
    "values": {
        "one": 1,
        "two": 2

When doing the following: self.client.post("/endpoint/", json.dumps(data)) one can stumble into JSON decoding errors, particularly with single/double quote issues.

The approach that I find works, which I still don’t love, is to alter the data object as follows:

data = {
    "values": json.dumps({
        "one": 1,
        "two": 2

Here th JSON encoding happens the the inner level of the data such that parsing the response like request.POST.get("values") results in the expected dictionary object.

Leave a comment