简体   繁体   中英

How can i serialize that dictionary in Django?

{'test': <Test: BOFEGRI_CGC_M: 2c942c01f8bfds498581a5d47d75fc020b-Started>, 'answers': <QuerySet [<TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 1, correct True>, <TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 2, correct False>, <TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 3, correct False>, <TestQuestionAnswer: 2c942c01f8b4ds98581a5d47d75fc020b: question nr. 3, answer nr. 4, correct False>]>, 'test_question': <TestQuestion: 2c942c01f8b4498581a5d47d75fc020b: nr=3>, 'test_button_list': [[{'number': 1, 'answered': False, 'correct': False}, {'number': 2, 'answered': False, 'correct': False}, {'number': 3, 'answered': False, 'correct': False}, {'number': 4, 'answered': False, 'correct': False}, {'number': 5, 'answered': False, 'correct': False}]], 'view': <tests.views.DifficultTestView object at 0x7f44e7e9c550>, 'form': <TestForm bound=False, valid=Unknown, fields=(AnswerRadioButton1;AnswerRadioButton2;AnswerRadioButton3;AnswerRadioButton4)>}

in my view:

context = self.get_context_data()
        print(self.get_context_data())
        html = render_to_string('difficult_test.html', context)

        if self.request.is_ajax():

            return http.JsonResponse({"html":html, "context":context})
        return response 

If i try to serialize i get this response: TypeError: is not JSON serializable

If you meant to ask how to serialize python object, so the 'pickle' built-in library allows that functionality.

Example:

import pickle

mapping = {'earth': [432, 762, 3297]}

result = pickle.dumps(mapping)
print(result)

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