Skip to content

Commit 90ef3aa

Browse files
Allow single values for JSON (#366)
Co-authored-by: jakirkham <[email protected]>
1 parent 45a8ef3 commit 90ef3aa

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

numcodecs/json.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,18 @@ def encode(self, buf):
5858
buf = np.asarray(buf)
5959
except ValueError:
6060
buf = np.asarray(buf, dtype=object)
61-
items = buf.tolist()
62-
items.extend((buf.dtype.str, buf.shape))
61+
items = np.atleast_1d(buf).tolist()
62+
items.append(buf.dtype.str)
63+
items.append(buf.shape)
6364
return self._encoder.encode(items).encode(self._text_encoding)
6465

6566
def decode(self, buf, out=None):
6667
items = self._decoder.decode(ensure_text(buf, self._text_encoding))
6768
dec = np.empty(items[-1], dtype=items[-2])
68-
dec[:] = items[:-2]
69+
if not items[-1]:
70+
dec[...] = items[0]
71+
else:
72+
dec[:] = items[:-2]
6973
if out is not None:
7074
np.copyto(out, dec)
7175
return out

numcodecs/tests/test_json.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import itertools
22

3-
43
import numpy as np
54
import pytest
65

@@ -65,11 +64,16 @@ def test_backwards_compatibility():
6564
(["11", "1", "1"], None),
6665
([{}], None),
6766
([{"key": "value"}, ["list", "of", "strings"]], object),
67+
([0], None),
68+
([{'hi': 0}], "object"),
69+
(["hi"], "object"),
70+
(0, None)
6871
]
6972
)
7073
def test_non_numpy_inputs(input_data, dtype):
7174
# numpy will infer a range of different shapes and dtypes for these inputs.
7275
# Make sure that round-tripping through encode preserves this.
76+
data = np.array(input_data, dtype=dtype)
7377
for codec in codecs:
74-
output_data = codec.decode(codec.encode(input_data))
75-
assert np.array_equal(np.array(input_data, dtype=dtype), output_data)
78+
output_data = codec.decode(codec.encode(data))
79+
assert input_data == output_data.tolist()

0 commit comments

Comments
 (0)