简体   繁体   English

如何配置Pyramid的JSON编码?

[英]How can I configure Pyramid's JSON encoding?

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: 由于Pyramid自己的JSON编码,它出现了双重编码,如下所示:

"{\"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. 我需要使用default参数 (或等效参数 ),因为它是Mongo自定义类型所必需的。

It seems like the dictionary is being JSON-encoded twice, the equivalent of: 看起来字典是JSON编码的两次,相当于:

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

Perhaps your Python framework automatically JSON-encodes the result? 也许你的Python框架会自动对结果进行JSON编码? 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 ). 要使用以您希望的方式生成JSON的自定义Pyramid渲染器,请尝试此操作(基于渲染器文档渲染器源 )。

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: 然后你有一个'json_with_custom_default'渲染器使用:

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

EDIT 2 编辑2

Another option could be to return a Response object which he renderer shouldn't modify. 另一种选择可能是返回一个他不应该修改的Response对象。 Eg 例如

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)

In addition to other excellent answers, I'd like to point out that if you don't want the data returned by your view function to be passed through json.dumps then you should not use renderer="json" in the view configuration :) 除了其他优秀的答案,我想指出,如果你不希望你的视图函数返回的数据通过json.dumps传递,那么你不应该在视图配置中使用renderer =“json”: )

So instead of 而不是

@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)

you can just use 你可以使用

@view_config(route_name='CreateNewAccount', request_method='GET', renderer='string')
def returnJSON(color, message=None):
    return  json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)

string renderer will just pass the string data returned by your function as-is. string renderer将只传递函数返回的字符串数据。 However, registering a custom renderer is a nicer approach (see @orip's answer) 但是,注册自定义渲染器是一种更好的方法(请参阅@ orip的答案)

You didn't say, but I will assume you are just using the standard json module. 你没有说,但我会假设你只是使用标准的json模块。

The json module doesn't define a class for JSON; json模块没有为JSON定义类; it uses a standard Python dict as the "native" representation of your data. 它使用标准的Python dict作为数据的“本机”表示。 json.dumps() encodes a dict as a JSON string; json.dumps()dict编码为JSON字符串; json.loads() takes a JSON string and gives back a dict . json.loads()接受一个JSON字符串并返回一个dict

So instead of doing this: 所以不要这样做:

def returnJSON(color, message=None):
    return  json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)

Try doing this: 试着这样做:

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

Just pass back a plain dict . 只是传回一个简单的dict See how your iPhone app likes this. 了解您的iPhone应用程序是如何喜欢这样

You are dumping the string of the Python object (dictionary) you are giving it. 您正在转储您提供的Python对象(字典) 字符串

The manual for json.dumps states: json.dumps手册指出:

Serialize obj to a JSON formatted str. 将obj序列化为JSON格式的str。

To convert back from the string, you will need to use the Python JSON function loads which LOADS a string into a JSON object. 要从字符串转换回来,您需要使用Python JSON函数加载 ,将LOADS字符串加载到JSON对象中。

What it appears you are trying to do however, is encode a python dictionary to JSON. 但是,你试图做的是将python字典encode为JSON。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM