def test_serialize_nested_list(): data = np.array([ [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7], ]) serialized_data = array_to_json(data) assert len(serialized_data) == 3 assert serialized_data[0]['dtype'] == 'int32' assert serialized_data[0]['value'] == memoryview(np.array(data[0])) assert serialized_data[1]['dtype'] == 'int32' assert serialized_data[1]['value'] == memoryview(np.array(data[1])) assert serialized_data[2]['dtype'] == 'int32' assert serialized_data[2]['value'] == memoryview(np.array(data[2])) deserialized_data = array_from_json(serialized_data) for el, deserialized_el in zip(data, deserialized_data): assert np.all(el == deserialized_el) data = np.array([[0, 1, 2, 3, 4, 5, 6], np.array([0, 1, 2, 2, 3]), [0, 1, 2, 3]]) serialized_data = array_to_json(data) assert len(serialized_data) == 3 assert serialized_data[0]['dtype'] == 'int32' assert serialized_data[0]['value'] == memoryview(np.array(data[0])) assert serialized_data[1]['dtype'] == 'int32' assert serialized_data[1]['value'] == memoryview(np.array(data[1])) assert serialized_data[2]['dtype'] == 'int32' assert serialized_data[2]['value'] == memoryview(np.array(data[2])) deserialized_data = array_from_json(serialized_data) for el, deserialized_el in zip(data, deserialized_data): assert np.all(el == deserialized_el) data = np.array([['Hello', 'Hallo'], ['Coucou', 'Hi', 'Ciao']]) serialized_data = array_to_json(data) assert len(serialized_data) == 2 assert serialized_data[0] == ['Hello', 'Hallo'] assert serialized_data[1] == ['Coucou', 'Hi', 'Ciao'] deserialized_data = array_from_json(serialized_data) assert np.all(data == deserialized_data)
def test_dtype_with_str(): # dtype object is not supported text = np.array(['foo', None, 'bar']) assert text.dtype == np.object with pytest.raises(ValueError, match='.*unsupported dtype: object.*'), pytest.warns(UserWarning): array_to_json(text) # but if they contain all strings, it should convert them. # This is for backward compatibility of expecting pandas dataframe # string columns to work (which are of dtype==np.object) text[1] = 'foobar' assert array_to_json(text) == ['foo', 'foobar', 'bar']
def double_list_array_to_json(double_list, obj=None): return [[array_to_json(k) for k in array_list] for array_list in double_list]