簡體   English   中英

Whoosh搜索結果無法序列​​化Json

[英]Whoosh search results not Json serializable

如何使Whoosh搜索結果的結果可序列化為JSON,以便可以將數據返回給客戶端?

Whoosh搜索輸出(python對象列表):

[<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"}>]

執行此操作時出錯:

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

我嘗試過另外一堂課

class DataSerializer(serializers.Serializer):

    icon=serializers.CharField()
    content=serializers.CharField()
    path=serializers.CharField()
    title=serializers.CharField()

但是錯誤變成Hit對象沒有屬性'icon'

正如@Igonato指出的那樣,如果將whoos_results包裝在dict ,則可以使它們whoos_results JSON serializable

response = dict(whoosh_results)
return JsonReponse({"data": response)

您甚至可以刪除字典的各個部分:

return JsonReponse({"content": response['content'], 'path': response['path']})

祝好運 :)

感覺有些丑陋,但這是可行的。 也許有人有更好的解決方案

return JsonReponse({"data": [dict(hit) for hit in whoosh_results]})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM