0

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'

user3226932
  • 2,042
  • 6
  • 39
  • 76

2 Answers2

2

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

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
0

Feels a bit ugly, but this works. Maybe somebody has a better solution

return JsonReponse({"data": [dict(hit) for hit in whoosh_results]})
user1383029
  • 1,685
  • 2
  • 19
  • 37