Skip to content

Commit 6f61dff

Browse files
committed
fix: fix issue ndarray of different dtype json compatibility
1 parent f71a5e6 commit 6f61dff

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

docarray/base_doc/docarray_response.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class DocArrayResponse(JSONResponse):
3333
---
3434
3535
```python
36-
from docarray.documets import Text
36+
from docarray.documents import Text
3737
from docarray.base_doc import DocResponse
3838
3939

docarray/typing/tensor/ndarray.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,9 @@
3131
from docarray.typing.tensor.tensorflow_tensor import TensorFlowTensor # noqa: F401
3232

3333
if TYPE_CHECKING:
34-
3534
from docarray.computation.numpy_backend import NumpyCompBackend
3635
from docarray.proto import NdArrayProto
3736

38-
3937
T = TypeVar('T', bound='NdArray')
4038
ShapeT = TypeVar('ShapeT')
4139

@@ -150,12 +148,12 @@ def _docarray_from_native(cls: Type[T], value: np.ndarray) -> T:
150148
return cast(T, value.view(cls.__unparametrizedcls__))
151149
return value.view(cls)
152150

153-
def _docarray_to_json_compatible(self) -> np.ndarray:
151+
def _docarray_to_json_compatible(self):
154152
"""
155153
Convert `NdArray` into a json compatible object
156154
:return: a representation of the tensor compatible with orjson
157155
"""
158-
return self.unwrap()
156+
return self.unwrap().tolist()
159157

160158
def unwrap(self) -> np.ndarray:
161159
"""

tests/units/array/test_array_from_to_json.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,27 @@ class MyDoc(BaseDoc):
149149
assert v_after._storage == v._storage
150150

151151

152+
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
153+
def test_from_to_json_doclist_different_dtype(dtype):
154+
emb = np.random.rand(128).astype(dtype)
155+
da = DocList[MyDoc](
156+
[
157+
MyDoc(embedding=emb, text='hello', image=ImageDoc(url='aux.png')),
158+
MyDoc(embedding=emb, text='hello world', image=ImageDoc()),
159+
]
160+
)
161+
json_da = da.to_json()
162+
da2 = DocList[MyDoc].from_json(json_da)
163+
assert len(da2) == 2
164+
assert len(da) == len(da2)
165+
for d1, d2 in zip(da, da2):
166+
assert d1.embedding.tolist() == d2.embedding.tolist()
167+
assert d1.text == d2.text
168+
assert d1.image.url == d2.image.url
169+
assert da[1].image.url is None
170+
assert da2[1].image.url is None
171+
172+
152173
def test_union_type():
153174
from typing import Union
154175

0 commit comments

Comments
 (0)