1

I am running a filter query in Django and my return results are as follows.

 search_result = [{'code': '12345', 'city': 'city1', 'country': 'USA', 'state': 'state1'}, {'code': '15675', 'city': 'city2', 'country': 'USA', 'state': 'state2'}]

I stored this returned data to a dictionary.

data_dict["return_result"] = search_result
data_dict["is_success"] = True

Now I am returning this data_dict as JsonResponse.(bcz this url was called using AJAX).

JsonResponse(data_dict)

In this process I am getting below error -

[{'code': '12345', 'city': 'city1', 'country': 'USA', 'state': 'state1'}, {'code': '15675', 'city': 'city2', 'country': 'USA', 'state': 'state2'}] is not JSON serializable.

Above mentioned data is a NOT a valid Json because of single quotes. If all single quotes are replaced with double quotes then this is a valid json.

Is there any way I can convert it to valid json or search query returns valid json.

Full Stack Trace:

Traceback (most recent call last):
  File "/home/rana/DjangoProject/VirtualEnv/e/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/rana/DjangoProject/VirtualEnv/e/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/rana/DjangoProject/VirtualEnv/e/lib/python3.4/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/rana/DjangoProject/Sanstha/sansthaonline/tenant/views/zip_city_search.py", line 37, in search_zip_city
    return JsonResponse(context)
  File "/home/rana/DjangoProject/VirtualEnv/e/lib/python3.4/site-packages/django/http/response.py", line 505, in __init__
    data = json.dumps(data, cls=encoder, **json_dumps_params)
  File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/home/rana/DjangoProject/VirtualEnv/e/lib/python3.4/site-packages/django/core/serializers/json.py", line 115, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'city': 'city1', 'country': 'USA', 'code': '12345', 'state': 'state1'}, {'city': 'city2', 'country': 'USA', 'code': '15675', 'state': 'state2'}] is not JSON serializable
Anurag Rana
  • 1,191
  • 2
  • 19
  • 46
  • Possible duplicate of [is not JSON serializable](http://stackoverflow.com/questions/16336271/is-not-json-serializable) – Selcuk Dec 07 '16 at 05:45
  • @Selcuk updated the question. – Anurag Rana Dec 07 '16 at 05:47
  • @Selcuk - as per my understanding, query return QuerySet type object which is not Json Serializable, but converting search_result to list convert the result into list type object, which is Json Serializable. Please comment if my understanding is not correct here. – Anurag Rana Dec 07 '16 at 06:42
  • You are right. You can either convert it to a list or use the special `DjangoJSONEncoder` as suggested in the answer below. – Selcuk Dec 08 '16 at 01:58

1 Answers1

1

This may help you:-

import json
from django.shortcuts import HttpResponse
from django.core.serializers.json import DjangoJSONEncoder

search_result = [{'code': '12345', 'city': 'city1', 'country': 'USA', 'state': 'state1'}, {'code': '15675', 'city': 'city2', 'country': 'USA', 'state': 'state2'}]


data = {'is_success':True,'msg':'Yor Success message','return_result':list(search_result)}

return HttpResponse(json.dumps(data,cls=DjangoJSONEncoder),content_type="application/json")
Piyush S. Wanare
  • 3,697
  • 2
  • 31
  • 44
  • converting search result to list worked very well. Is this standard way to do it or just a hack? Could you please explain why your code works and my code dosn't work – Anurag Rana Dec 07 '16 at 06:27
  • your query result looks like you used `.values()` , have you? Try to use direct `.filter`, may be it works. – Piyush S. Wanare Dec 07 '16 at 07:16