python序列化和反序列化对象内的numpy数组

时间:2018-03-21 22:14:28

标签: python json numpy serialization codec

我想把一个Python对象和序列化/反序列化到/从JSON。该对象内部有numpy数组:

class Student(object):
    name = ""
    age = 0
    major = ""
    teacher = ""
    #tuple1 = (1,2,3)
    #tuple2 = ("a","b","c")
    ndarr = ""

    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

我目前正在使用jsonpickle将其序列化为json。

frozen = jsonpickle.encode(obj)
print "jsonpickle serialized object: " + frozen

然而,在我序列化之后,numpy数组看起来很奇怪:

jsonpickle序列化对象:

{"py/object": "Student.Student", "age": 21, "major": "eecs", "ndarr": {"py/reduce": [{"py/object": "__builtin__.builtin_function_or_method"}, {"py/tuple": [{"py/type": "numpy.ndarray"}, {"py/tuple": [0]}, "b"]}, {"py/tuple": [1, {"py/tuple": [2, 2]}, {"py/reduce": [{"py/type": "numpy.dtype"}, {"py/tuple": ["f8", 0, 1]}, {"py/tuple": [3, "<", null, null, null, -1, -1, 0]}, null, null]}, true, {"py/b64": "2MfF58x/AADYx8XnzH8AAAAAAAAAAAAAAAAAAAAAAAA=\n"}]}, null, null]}, "name": "larry"}

有一种简单的方法来序列化另一个对象内的numpy数组对象吗?我发现这篇文章中的第一个答案是可行的,但它不在一个对象中:NumPy array is not JSON serializable

0 个答案:

没有答案