I am trying to read the response of the server that gives me the following JSON:
{"result": "Success", "message": "[{\"model\": \"mysite.userprofile\", \"pk\": 1}, {\"model\": \"mysite.userprofile\", \"pk\": 4}]"}
When I try to read it I get as is a String. If I try to parse it is not possible as it gives me
Unexpected token o in JSON at position 1
which means that is a Json already.
So this code:
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: '/search/?city=&radius=',
success: function (data) {
//data = JSON.parse(data);
var ul = document.getElementById("contact-list");
console.log("JSON? "+data.message[0]); // Print [ which is the first char
for (var x = 0; x < data.message.length; x++){
// iterate throw every character in the message
}
So inside the properties ('result' and 'message') it appears as there is a String instead of a Json
And here is the server side:
def search_profiles_by_loc(request):
if request.method == "POST" and request.is_ajax():
city = request.POST.get('city', False)
all_profiles = UserProfile.objects.all()
response_data = {}
response_data['result'] = 'Success'
response_data['message'] = serializers.serialize('json', all_profiles)
return HttpResponse(JsonResponse(response_data), content_type="application/json")
I tried a lot of things nothing work
JSON.parse()on the string. Or send it as an array, without enclosing with"messagein the backend before you add it to the response. You should fix that mistake on the server rather than trying to work around this in the client.