python - SimpleJSON 和 NumPy 数组

标签 python json numpy simplejson

使用 simplejson 序列化 numpy 数组的最有效方法是什么?

最佳答案

为了保持数据类型和维度,试试这个:

import base64
import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):

    def default(self, obj):
        """If input object is an ndarray it will be converted into a dict 
        holding dtype, shape and the data, base64 encoded.
        """
        if isinstance(obj, np.ndarray):
            if obj.flags['C_CONTIGUOUS']:
                obj_data = obj.data
            else:
                cont_obj = np.ascontiguousarray(obj)
                assert(cont_obj.flags['C_CONTIGUOUS'])
                obj_data = cont_obj.data
            data_b64 = base64.b64encode(obj_data)
            return dict(__ndarray__=data_b64,
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        # Let the base class default method raise the TypeError
        super(NumpyEncoder, self).default(obj)


def json_numpy_obj_hook(dct):
    """Decodes a previously encoded numpy ndarray with proper shape and dtype.

    :param dct: (dict) json encoded ndarray
    :return: (ndarray) if input was an encoded ndarray
    """
    if isinstance(dct, dict) and '__ndarray__' in dct:
        data = base64.b64decode(dct['__ndarray__'])
        return np.frombuffer(data, dct['dtype']).reshape(dct['shape'])
    return dct

expected = np.arange(100, dtype=np.float)
dumped = json.dumps(expected, cls=NumpyEncoder)
result = json.loads(dumped, object_hook=json_numpy_obj_hook)


# None of the following assertions will be broken.
assert result.dtype == expected.dtype, "Wrong Type"
assert result.shape == expected.shape, "Wrong Shape"
assert np.allclose(expected, result), "Wrong Values"

关于python - SimpleJSON 和 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3488934/

相关文章:

iphone - 使用 JSON 搜索 MKMapview 往往不会返回任何结果,或者返回不正确的结果

python - 在Python中以对数尺度插值

python - 仅当其值不属于特定数据类型时才连接 3+ 列

python - TensorFlow ValueError : Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder : 0', which has shape ' (? , 64, 64, 3)'

Python-Matplotlib : plotting pivot table for hydrological year

python - .get 和字典

python - 有没有好方法在 numpy 数组上进行 "moving"计算?

python - 在同一行中绘制 2 个 seaborn KDE 联合图

javascript - 如何管理reactjs状态下保存的数组

javascript - JSONArray 创建后出现额外的数字