Skip to content

Commit 3fdd10e

Browse files
committed
iterator on objects
1 parent d6d0ace commit 3fdd10e

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

adafruit_json_stream.py

+35
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,41 @@ def __getitem__(self, key):
239239
self.done = self.data.fast_forward(",")
240240
raise KeyError(key)
241241

242+
def __iter__(self):
243+
return self
244+
245+
def _next_item(self):
246+
"""Return the next item as a (key, value) pair, regardless of key."""
247+
if self.active_child:
248+
self.active_child.finish()
249+
self.done = self.data.fast_forward(",")
250+
self.active_child = None
251+
if self.done:
252+
raise StopIteration()
253+
254+
current_key = self.data.next_value(":")
255+
if current_key is None:
256+
self.done = True
257+
raise StopIteration()
258+
259+
next_value = self.data.next_value(",")
260+
if self.data.last_char == ord("}"):
261+
self.done = True
262+
if isinstance(next_value, Transient):
263+
self.active_child = next_value
264+
return (current_key, next_value)
265+
266+
def __next__(self):
267+
return self._next_item()[0]
268+
269+
def items(self):
270+
"""Return iterator ine the dictionary’s items ((key, value) pairs)."""
271+
try:
272+
while not self.done:
273+
yield self._next_item()
274+
except StopIteration:
275+
return
276+
242277

243278
def load(data_iter):
244279
"""Returns an object to represent the top level of the given JSON stream."""

tests/test_json_stream.py

+19
Original file line numberDiff line numberDiff line change
@@ -685,3 +685,22 @@ def test_as_object_grabbing_multiple_subscriptable_levels_again_after_passed_rai
685685
assert next(dict_1["sub_list"]) == "a"
686686
with pytest.raises(KeyError, match="sub_dict"):
687687
dict_1["sub_dict"]["sub_dict_name"]
688+
689+
690+
def test_iterating_keys(dict_with_keys):
691+
"""Iterate through keys of a simple object"""
692+
693+
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
694+
stream = adafruit_json_stream.load(bytes_io_chunk)
695+
output = list(stream)
696+
assert output == ["field_1", "field_2", "field_3"]
697+
698+
699+
def test_iterating_items(dict_with_keys):
700+
"""Iterate through items of a simple object"""
701+
702+
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
703+
stream = adafruit_json_stream.load(bytes_io_chunk)
704+
output = list(stream.items())
705+
assert output == [("field_1", 1), ("field_2", 2), ("field_3", 3)]
706+

0 commit comments

Comments
 (0)