Skip to content

Commit f2ed1a1

Browse files
committed
add example that uses .items() and tests for iterating after already accessing an item
1 parent 3fdd10e commit f2ed1a1

File tree

2 files changed

+84
-2
lines changed

2 files changed

+84
-2
lines changed

examples/json_stream_advanced.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2023 Scott Shawcroft for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
import sys
6+
import time
7+
8+
import adafruit_json_stream as json_stream
9+
10+
# import json_stream
11+
12+
13+
class FakeResponse:
14+
def __init__(self, file):
15+
self.file = file
16+
17+
def iter_content(self, chunk_size):
18+
while True:
19+
yield self.file.read(chunk_size)
20+
21+
22+
f = open(sys.argv[1], "rb") # pylint: disable=consider-using-with
23+
obj = json_stream.load(FakeResponse(f).iter_content(32))
24+
25+
26+
def find_keys(obj, keys):
27+
"""If we don't know the order in which the keys are,
28+
go through all of them and pick the ones we want"""
29+
out = dict()
30+
# iterate on the items of an object
31+
for key, value in obj.items():
32+
if key in keys:
33+
# if it's a sub object, get it all
34+
if isinstance(value, json_stream.Transient):
35+
value = value.as_object()
36+
out[key] = value
37+
return out
38+
39+
def time_to_date(stamp):
40+
tt = time.localtime(stamp)
41+
month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][tt.tm_mon]
42+
return f"{tt.tm_mday:2d}th of {month}"
43+
44+
def ftoc(temp):
45+
return (temp - 32) * 5 / 9
46+
47+
currently = obj["currently"]
48+
print("Currently:")
49+
print(" ", time_to_date(currently["time"]))
50+
print(" ", currently["icon"])
51+
52+
# iterate on the content of a list
53+
for i, day in enumerate(obj["daily"]["data"]):
54+
day_items = find_keys(day, ("time", "summary", "temperatureHigh"))
55+
date = time_to_date(day_items["time"])
56+
print(
57+
f'On {date}: {day_items["summary"]},',
58+
f'Max: {int(day_items["temperatureHigh"])}F',
59+
f'({int(ftoc(day_items["temperatureHigh"]))}C)'
60+
)
61+
62+
if i > 4:
63+
break

tests/test_json_stream.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -688,7 +688,7 @@ def test_as_object_grabbing_multiple_subscriptable_levels_again_after_passed_rai
688688

689689

690690
def test_iterating_keys(dict_with_keys):
691-
"""Iterate through keys of a simple object"""
691+
"""Iterate through keys of a simple object."""
692692

693693
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
694694
stream = adafruit_json_stream.load(bytes_io_chunk)
@@ -697,10 +697,29 @@ def test_iterating_keys(dict_with_keys):
697697

698698

699699
def test_iterating_items(dict_with_keys):
700-
"""Iterate through items of a simple object"""
700+
"""Iterate through items of a simple object."""
701701

702702
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
703703
stream = adafruit_json_stream.load(bytes_io_chunk)
704704
output = list(stream.items())
705705
assert output == [("field_1", 1), ("field_2", 2), ("field_3", 3)]
706706

707+
708+
def test_iterating_keys_after_get(dict_with_keys):
709+
"""Iterate through keys of a simple object after an item has already been read."""
710+
711+
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
712+
stream = adafruit_json_stream.load(bytes_io_chunk)
713+
assert stream["field_1"] == 1
714+
output = list(stream)
715+
assert output == ["field_2", "field_3"]
716+
717+
718+
def test_iterating_items_after_get(dict_with_keys):
719+
"""Iterate through items of a simple object after an item has already been read."""
720+
721+
bytes_io_chunk = BytesChunkIO(dict_with_keys.encode())
722+
stream = adafruit_json_stream.load(bytes_io_chunk)
723+
assert stream["field_1"] == 1
724+
output = list(stream.items())
725+
assert output == [("field_2", 2), ("field_3", 3)]

0 commit comments

Comments
 (0)