Python Web服务返回布尔数组到Angular端为字符串如何解决
根因说明
- 前端收到字符串类型的布尔数组:你构造返回结果时对
isKeyWindowSegmentRepresentative单独执行了json.dumps(),相当于把数组先序列化为字符串。整个响应体后续会被Web框架再做一次JSON序列化,该字段被二次序列化后到前端就变成了字符串格式。 - 二维列表转numpy报错:从日志可以看到
pixelsValuesSatisfyThresholdInWindowSegment是二维列表,每个元素本身还是列表,直接传入np.array()指定dtype=float时,无法将列表类型转为float,触发报错。
修复方案
修复布尔数组返回格式
不需要对单个字段做单独序列化,直接赋值数组即可,修改返回的字典构造逻辑:
resultsDict = { # 去掉多余的json.dumps调用,直接传入列表 "isKeyWindowSegmentRepresentative": np.array(isKeyWindowSegmentRepresentative, dtype=bool).tolist() }
如果isKeyWindowSegmentRepresentative本身就是Python原生布尔列表,可跳过numpy转换,直接赋值:
"isKeyWindowSegmentRepresentative": isKeyWindowSegmentRepresentative
修改后框架序列化响应时会自动将该字段转为JSON数组,前端Angular直接就能拿到布尔数组类型的值。
修复二维数组转换报错
如果要保留二维结构返回,直接正常构造numpy数组即可,numpy原生支持二维列表转换:
"pixelsValuesSatisfyThresholdInWindowSegment": np.array(pixelsValuesSatisfyThresholdInWindowSegment, dtype=float).tolist()
如果需要转为一维数组返回,先对二维列表做展平处理:
# 先把二维列表展平为一维,再做转换 flatten_list = [item for sublist in pixelsValuesSatisfyThresholdInWindowSegment for item in sublist] "pixelsValuesSatisfyThresholdInWindowSegment": np.array(flatten_list, dtype=float).tolist()
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

