TypeError: EnvironHeaders([•••]) is not JSON serializable

Viewed 5787

I want to turn incoming HTTP requests' headers into dictionaries and clone then via the "JSON trick." request.headers is an object that acts like a dictionary, but actually isn't a dictionary.

json.loads(json.dumps(request.headers))

The above-mentioned line of code results in this error:

TypeError: EnvironHeaders([•••]) is not JSON serializable

How do I convert a werkzeug.datastructures.EnvironHeaders object to a dictionary?


Attempt #1:

json.loads(json.dumps({k: v for k, v in request.headers.iteritems()}))

Attempt #2:

json.loads(json.dumps({k: request.headers[k] for k in request.headers.keys()}))

Both of them throw this exception:

ValueError: too many values to unpack

1 Answers

Here is a minimal example that works for sure

headers = werkzeug.datastructures.Headers()
headers.add('Content-Type', 'text/plain')
headers.add('X-Foo', 'bar')
json.dumps({k:v for k, v in headers.iteritems()})

Even if you are using EnvironHeaders,

env = {
    'HTTP_CONTENT_TYPE':        'text/html',
    'CONTENT_TYPE':             'text/html',
    'HTTP_CONTENT_LENGTH':      '0',
    'CONTENT_LENGTH':           '0',
    'HTTP_ACCEPT':              '*',
    'wsgi.version':             (1, 0)
}
headers = werkzeug.datastructures.EnvironHeaders(env)
json.dumps({k:v for k, v in headers.iteritems()})

(Examples copied from test cases in werkzeug.)

Have you inspected request.headers.items() in a debugger?

Like so,

items = request.headers.items()
import ipdb
ipdb.set_trace()   # check type of items; is it an iterable of pairs?
Related