'Object of type 'AttrList' is not JSON serializable
class SearchSuggest(View):
def get(self, request):
key_words = request.GET.get('s','')
re_datas = []
if key_words:
s = JobType.search()
s = s.suggest('my_suggest', key_words, completion={
"field":"suggest", "fuzzy":{
"fuzziness":2
},
"size": 10
})
suggestions = s.execute_suggest()
for match in suggestions.my_suggest[0].options:
source = match._source
re_datas.append(str(source["job_name"]))
# return HttpResponse(json.dumps(re_datas), content_type="application/json")
return HttpResponse(json.dumps(re_datas), content_type="application/json")
# re_datas=list(re_datas)
But the result :
So how can i fix this? thanks!I expect not list type! I hope the view in the browser was the str but not list.I'm trying to fix it.
Solution 1:[1]
Can you try replacing re_datas.append(source["job_name"]) with:
re_datas.append(str(source["job_name"]))
Looks like from your image that re_datas should basically be a list of strings.
The problem is likely that source["job_name"] is returning an object that json does not understand how to serialize. If you just need the string representation of this object, try getting it with str(source["job_name"]).
If it is more complex you will need to make your class json serializable - check out How to make a class JSON serializable
Solution 2:[2]
[ x for x in source["job_name"] ]
or
[ *source["job_name"] ]
source['job_name'] (AttrList) can be iterated and stored in an array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |

