【问题标题】:how to serialize array of booleans如何序列化布尔数组
【发布时间】:2021-09-27 14:23:05
【问题描述】:

我有一个用 python 编写的 web 服务。它从 angular code.in 网络服务的 python 代码中调用,如下所示,网络服务返回 isKeyWindowSegmentRepresentative 这是一个布尔数组 .当从角度代码调用服务时,我收到isKeyWindowSegmentRepresentative 作为字符串。 我想将上述数组作为包含布尔值的数组接收,这样我就可以遍历它的内容。 Web 服务返回的内容和 Angular 代码显示的是以下字符串:

isKeyWindowSegmentRepresentative: "[false, false, true, true, false, false, true, true, true, true]"

我想将它作为一个布尔数组接收。

注意:

它不是一个 numpy 数组。它是一个普通数组,声明如下: isKeyWindowSegmentRepresentative=[]

更新

for:  "pixelsValuesSatisfyThresholdInWindowSegment":np.array(pixelsValuesSatisfyThresholdInWindowSegment,dtype=float).tolist()
i recieve the following error:

    TypeError: float() argument must be a string or a number, not 'list'

the pixelsValuesSatisfyThresholdInWindowSegment contains _pixelsValuesSatisfyThresholdInWindowSegment
            logger.debug(type(pixelsValuesSatisfyThresholdInWindowSegment)):<class 'list'>
            logger.debug(type(pixelsValuesSatisfyThresholdInWindowSegment[0])):<class 'list'>
            logger.debug(type(_pixelsValuesSatisfyThresholdInWindowSegment)):<class 'list'>
            logger.debug(type(_pixelsValuesSatisfyThresholdInWindowSegment[0]))::<class 'numpy.float32'>

从 python 代码返回字典为 json

    resultsDict = {
        "isKeyWindowSegmentRepresentative":json.dumps(np.array(isKeyWindowSegmentRepresentative, dtype=bool).tolist())
        }

【问题讨论】:

  • 你为什么使用 numpy (np)?
  • 那么为什么要使用np.array(...).tolist()?从列表到 numpy 数组再到列表似乎是循环的。
  • @ogdenkev 因为我收到 bool_ 类型的对象不是 JSON 可序列化的

标签: python json bson


【解决方案1】:

只是不要将列表转储为字典中的字符串,而且您似乎有一些不可序列化 JSON 的 numpy 数据类型,请先转换它们:

resultsDict = {
    "isKeyWindowSegmentRepresentative": [bool(x) for x in isKeyWindowSegmentRepresentative]
}

同样,如果你有 numpy 浮点数,使其 JSON 可序列化:

resultsDict = {
    "isKeyWindowSegmentRepresentative": [float(x) for x in isKeyWindowSegmentRepresentative]
}

【讨论】:

  • 它您提供的方法也适用于浮点数组?如果是,请提供示例
  • 你在找什么样的例子?应该是一样的。我想这里唯一需要注意的是。 numpy 数组不可序列化,因此在通过网络发送之前将其转换为列表。
  • 其实我和@ogdenkev 有同样的问题,你为什么在这里使用numpy?不能直接用isKeyWindowSegmentRepresentative吗?
  • 我收到 bool_ 类型的对象不是 JSON 可序列化的,当我只使用 isKeyWindowSegmentRepresentative 时
  • 请您看看上面发布的更新部分
【解决方案2】:

从 cmets 中,我了解到 isKeyWindowSegmentRepresentative 变量是一个 dtype bool 的 NumPy 数组。

isKeyWindowSegmentRepresentative = np.array([True, False, False, True])

resultsDict = {
    "isKeyWindowSegmentRepresentative": isKeyWindowSegmentRepresentative.tolist()
}

如果它是 float 类型,它也应该可以工作,因为 float 是 JSON 可序列化的。

my_floats = np.array([1.1, 2.2, 3.3, 4.4])

resultsDict = {
    "my_floats": my_floats.tolist()
}

它可能不适用于每种数据类型,因为NumPy arrays are not JSON serializable

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 2011-10-05
    • 1970-01-01
    • 2016-08-22
    • 2015-07-03
    • 2016-09-11
    • 2019-04-04
    • 2020-07-31
    • 2021-04-06
    相关资源
    最近更新 更多