Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of dictionaries to JSON in Python / Django?

I searched on Google and found an answer but it's not working for me. I have to send a list as JsonResponse in Django, similar to this:

list_to_json =[{"title": "hello there",
                "link": "www.domain.com",
                "date":   ...},
               {},{},{},...]

I am converting this to JSON by applying StackOverflow question1 and question2 but it's not working for me. I get the following error:

In order to allow non-dict objects to be serialized set the safe parameter to False

Here's my code:

    def json_response(request):
        list_to_json=[{"title": ..., "link": ..., "date": ...},{...}]
        return JsonResponse(json.dumps(list_to_json) )
like image 870
shuboy2014 Avatar asked Jun 19 '16 17:06

shuboy2014


1 Answers

return JsonResponse(list_to_json, safe=False)

Take a look at the documentation:

The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised.

like image 55
Adam Hopkins Avatar answered Sep 28 '22 01:09

Adam Hopkins