【问题标题】:Serializing dictionary of lists not working "TypeError: 0.031 is not JSON serializable"序列化列表字典不起作用“TypeError:0.031 不是 JSON 可序列化”
【发布时间】:2016-05-19 16:56:07
【问题描述】:

对于以下代码:

document_vectors = dict()
for label in d2v_model.docvecs.doctags:
    vector = [ v for v in d2v_model.docvecs[label]]
    document_vectors[label] = list(vector)

document_vectors_file ="../results/amazon_hierarchical_document_vectors.json"

with open(document_vectors_file, "w") as outfile:
    print "Writing document vectors .."
    json.dumps(document_vectors, outfile)

我得到:

TypeError: 0.031942371 is not JSON serializable

调试它告诉我,我确实在这里有一个dict()list()(我也尝试只使用一个简单的数组),但它不起作用。为什么?

【问题讨论】:

    标签: python json serialization


    【解决方案1】:

    有趣的是这个成功了:

    vector = [1.0*v for v in d2v_model.docvecs[label]]
    

    调试器说d2v_model.docvecs[label] 返回一个float32,但是json 对此并不满意。乘以1.0 将其转换为float64,它会突然起作用。

    可能与Convert numpy type to python有关

    【讨论】:

      猜你喜欢
      • 2018-02-10
      • 1970-01-01
      • 2017-10-24
      • 2016-08-02
      • 2019-02-08
      • 2013-05-11
      • 2015-12-04
      • 1970-01-01
      • 2014-08-13
      相关资源
      最近更新 更多