How do I make the results from Whoosh search results JSON serializable so I can return that data back to the client?
Whoosh search output (list of python objects):
[<Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}>, <Hit {'content': 'Examples are many second.', 'path': '/c', 'icon': '/icons/book.png', 'title': "Third time's the charm"}>]
Error when doing this:
return JsonReponse({"data": whoosh_results})
TypeError: <Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}> is not JSON serializable
I have tried making a separate class
class DataSerializer(serializers.Serializer):
icon=serializers.CharField()
content=serializers.CharField()
path=serializers.CharField()
title=serializers.CharField()
but the error becomes that the Hit object has no attribute 'icon'
As @Igonato points out, if you wrap your whoos_results
in a dict
you can make them JSON serializable
:
response = dict(whoosh_results)
return JsonReponse({"data": response)
You can even take individual parts of your dictionary out:
return JsonReponse({"content": response['content'], 'path': response['path']})
Good luck :)