Python Pyramid not rendering JSON correctly -
i using mongoengine's to_json
method on object wish render in json-rendered pyarmid page. i've done lots of json rendering in pyramid, not mongoengine. mongoengine's to_json
method simple calls json_util.dumps
. works fine in python. problem when pyramid renders page, rendered this:
{ "0": "\"", "1": "{", "2": "\\", "3": "\"", "4": "_", etc...
however, json dump looks ok in python, before rendered:
'{"_id": {"$oid": "4ebca43ccc7a67085b000000"}, "created": {"$date": 1346419407715}, "modified": {"$date": 1403757381829}, "modified_by": {"$oid": "4ebca43ccc7a67085b000000"}, "email": etc...
as has been suggested in comments, seems json being jsonified more once, can't figure out where.
i pick user
object database , attach every request:
def get_user(request): return user.objects(id=objectid(authenticated_userid(request))).first() config.add_request_method(get_user, 'user', reify=true)
i return user per request:
@view_config(route_name='api.user', permission='authenticated', renderer='json') def user_vc(request): response = request.response _id = request.matchdict['id'] if _id == 'session': user = request.user if not user: response.status = 403 return response else: print user # user object expected (not json) return user
i have custom adapter handle user
object:
# custom json adapters custom_json = json() def user_adapter(obj, request): print obj.to_json() # json looks ok here return obj.to_json() custom_json.add_adapter(user, user_adapter) config.add_renderer('json', custom_json)
i not doing other jsonification myself, apart adapter above. is?? great.
thanks comment @anttihappala above, found problem. mongoengine's to_json
method converts objects jsonified string. however, pyramid needs json data structure. so, fix it, added following function custom renderer:
def render_to_json(obj): return json.loads(obj.to_json()) def user_adapter(obj, request): return render_to_json(obj) custom_json.add_adapter(user, user_adapter)
i can add custom renderer other mongoengine objects , return them natively.
Comments
Post a Comment