Azure 函数:返回 JSON 对象 [英] Azure functions: return JSON object
问题描述
考虑:
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = {"test":"jjj"}
return func.HttpResponse(name)
以上是我使用 Python 预览的 Azure 函数 (V2).
Above is my Azure function (V2) using Python preview.
如果我回来
func.HttpResponse(f"{name}")
它有效,但如果我返回一个 dict 对象,它就不会.
it works, but if I return a dict object it does not.
显示的错误是:
Exception: TypeError: reponse is expected to be an str, bytes, or bytearray, got dict
Exception: TypeError: reponse is expected to be either of str, bytes, or bytearray, got dict
推荐答案
您需要使用内置 JSON 库将您的字典转换为 JSON 字符串 - json.dumps.
You need to convert your dictionary to a JSON string using the built-in JSON library - json.dumps.
然后您可以将函数的 MIME 类型(Content-Type)设置为应用程序/json
.默认情况下 Azure 函数 HttpResponse 返回 text/plain
内容类型.
Then you can set the MIME type (Content-Type) of your function to application/json
. By default Azure functions HttpResponse returns text/plain
Content-Type.
import json
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = {"test":"jjj"}
return func.HttpResponse(
json.dumps(name),
mimetype="application/json",
)
这篇关于Azure 函数:返回 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!