Botond Botond - 1 year ago 105
JSON Question

Django REST undefined JSON

I am trying to accomplish a country name autocomplete with Django's REST framework and AJAX. The relevant parts are here:

#---- -------------
def get_country(request):
if request.method == 'POST':
#JSON to serializer object
serializer = CountrySerializer(
if (serializer.is_valid() == False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

req_name = serializer.validated_data['country_name']
matching_countries = Country.objects.filter(country_name__icontains = req_name )[:20]
country_json = {}
country_json['country_name'] = []
for c in matching_countries:
return JsonResponse(country_json)

// ---- client side call
function get_country(query, process) {
url: 'get_country/',
type: 'POST',
dataType: 'json',
data: {
country_name: query
success: function (response) {
s =;

The request seems to work, if I check the response in the chrome developer tools, I get something like:

{"country_name": ["BHUTAN", "HUNGARY", "LITHUANIA"]}

The problem is that the response object seems to have undefined type. The line console.log(typeof(eval(s))); prints undefined in the console. I tried various ways to parse, stringify, but none of them seemed to work. Any idea on what is going on? I have to keep the above structure for the response to plug it in another function later on.


According to the docs, the success function has this signature:

Function( Anything data, String textStatus, jqXHR jqXHR )

For example:

success: function (data, status, xhr) { console.log(data.country_name[0] === 'BHUTAN'); // Prints true }