TypeError:array(['cycling'],dtype = object)不是JSON可序列化的

时间:2017-11-07 11:23:09

标签: python json django serialization machine-learning

嗨我已经制作了一个文本分类分类器,我在这里使用它返回一个数组,我想返回jsonresponse但最后一行代码给我错误'array(['cycling'],dtype = object)不是JSON serializable'

def classify_text(request):
    if request.method == 'POST' and request.POST.get('text'):
        test = []
        text = request.POST.get('text')
        text = re.sub('[^a-zA-Z]', ' ', text)
        text = text.lower()
        text = text.split()
        ps = PorterStemmer()
        text = [ps.stem(word) for word in text if not word in set(stopwords.words('english'))]
        text = ' '.join(text)
        test.append(text)

        pred = cv.transform(test).toarray()
        pred = svm_model_linear.predict(pred)
        return JsonResponse(pred, safe=False)

1 个答案:

答案 0 :(得分:2)

您需要将numpy array转换为list对象,这可以使用numpy数组对象上的.tolist()方法轻松完成。

示例

pred_list = pred.tolist()
return JsonResponse(pred_list, safe=False)