How can I configure Pyramid's JSON encoding?

json, pymongo, pyramid, python

Solution

It seems like the dictionary is being JSON-encoded twice, the equivalent of:

json.dumps(json.dumps({ "color" : "color", "message" : "message" }))

Perhaps your Python framework automatically JSON-encodes the result? Try this instead:

def returnJSON(color, message=None):
  return { "color" : "color", "message" : "message" }

EDIT:

To use a custom Pyramid renderer that generates JSON the way you want, try this (based on the renderer docs and the renderer sources).

In startup:

from pyramid.config import Configurator
from pyramid.renderers import JSON

config = Configurator()
config.add_renderer('json_with_custom_default', JSON(default=json_util.default))

Then you have a 'json_with_custom_default' renderer to use:

@view_config(route_name='CreateNewAccount', request_method='GET', renderer='json_with_custom_default')

EDIT 2

Another option could be to return a `Response` object which he renderer shouldn't modify. E.g.

from pyramid.response import Response
def returnJSON(color, message):
  json_string = json.dumps({"color": color, "message": message}, default=json_util.default)
  return Response(json_string)

Problem

I'm trying to return a function like this: ``` @view_config(route_name='CreateNewAccount', request_method='GET', renderer='json') def returnJSON(color, message=None): return json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default) ``` Because of Pyramid's own JSON encoding, it's coming out double-encoded like this: ``` "{\"color\": \"color\", \"message\": \"message\"}" ``` How can I fix this? I need to use the `default` argument (or equivalent) because it's required for Mongo's custom types.

Original source