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

时间:2016-05-18 19:04:40

标签: python json

我有一个python函数/方法,它接收一个学生并将显示配置文件...我意识到我需要将上下文作为json字符串返回。我该怎么做?

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?

如何将上下文作为json字符串返回?

1 个答案:

答案 0 :(得分:3)

导入json库:

import json

然后使用json.dumps

return json.dumps(context)

来自Python documentation

  

<强> json.dumps(obj, ...)

     

将obj序列化为格式为str

的JSON