Home > OS >  how to serialize array of booleans
how to serialize array of booleans

Time:09-28

i have a webservice written in python. and it gets invoked from angular code.in python code of the web-service, as shown below, the web-service returns isKeyWindowSegmentRepresentative which is an array of boolean . when the service is invoked from angular code i receive the isKeyWindowSegmentRepresentative as string. i want to receive the aforementioned array as an array the contains boolean value so i can iterate through its contents. what the web-service returns and what the angular code shows is the following string :

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

i would like to receive it as an array of boolean.

Note:

it is not a numpy array. it is a normal array declared as follows: isKeyWindowSegmentRepresentative=[]

update:

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'>

returned dictionary from python code as json:

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

CodePudding user response:

Just don't dump the list as string in your dictionary, also it seems you have some numpy data type which is not JSON serializable, convert them first:

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

Similarly if you have numpy floats, to make it JSON serializable:

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

CodePudding user response:

From the comments, I gather that the isKeyWindowSegmentRepresentative variable is a NumPy array of dtype bool.

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

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

If it is of type float, it should also work because floats are JSON serializable.

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

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

It may not work for every data type because NumPy arrays are not JSON serializable.

  • Related