shuboy2014 shuboy2014 - 5 months ago 441
JSON Question

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) )

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

Comments