简体   繁体   中英

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. 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?

Import the json library:

import json

Then use json.dumps :

return json.dumps(context)

From the Python documentation :

json.dumps(obj, ...)

Serialize obj to a JSON formatted str

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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