簡體   English   中英

如何配置Pyramid的JSON編碼?

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

我正在嘗試返回這樣的函數:

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

由於Pyramid自己的JSON編碼,它出現了雙重編碼,如下所示:

"{\"color\": \"color\", \"message\": \"message\"}"

我怎樣才能解決這個問題? 我需要使用default參數 (或等效參數 ),因為它是Mongo自定義類型所必需的。

看起來字典是JSON編碼的兩次,相當於:

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

也許你的Python框架會自動對結果進行JSON編碼? 試試這個:

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

編輯:

要使用以您希望的方式生成JSON的自定義Pyramid渲染器,請嘗試此操作(基於渲染器文檔渲染器源 )。

在啟動時:

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

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

然后你有一個'json_with_custom_default'渲染器使用:

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

編輯2

另一種選擇可能是返回一個他不應該修改的Response對象。 例如

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)

除了其他優秀的答案,我想指出,如果你不希望你的視圖函數返回的數據通過json.dumps傳遞,那么你不應該在視圖配置中使用renderer =“json”: )

而不是

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

你可以使用

@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將只傳遞函數返回的字符串數據。 但是,注冊自定義渲染器是一種更好的方法(請參閱@ orip的答案)

你沒有說,但我會假設你只是使用標准的json模塊。

json模塊沒有為JSON定義類; 它使用標准的Python dict作為數據的“本機”表示。 json.dumps()dict編碼為JSON字符串; json.loads()接受一個JSON字符串並返回一個dict

所以不要這樣做:

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

試着這樣做:

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

只是傳回一個簡單的dict 了解您的iPhone應用程序是如何喜歡這樣

您正在轉儲您提供的Python對象(字典) 字符串

json.dumps手冊指出:

將obj序列化為JSON格式的str。

要從字符串轉換回來,您需要使用Python JSON函數加載 ,將LOADS字符串加載到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