简体   繁体   English

在需要python dict的函数之后将对象转换为json字符串

[英]convert object to json string after function that needs python dict

I have a python function/method that takes in a student and will show profile... i realized i need to return context as a json string. 我有一个带学生的python函数/方法,它将显示配置文件...我意识到我需要将上下文作为json字符串返回。 how do i do that? 我怎么做?

context["student"] = db.query_dict(student_profile_sql.format(student_id=self.kwargs["student_id"])
    )[0]

appear(self.request, "Show profile", {
   "student_name": context["student"]["first_name...
})

return context  // i need to return context as json string how can i do that?

How can i return context as a json string? 如何返回上下文作为json字符串?

Import the json library: 导入json库:

import json

Then use json.dumps : 然后使用json.dumps

return json.dumps(context)

From the Python documentation : Python文档中

json.dumps(obj, ...)

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

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

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