Back to snippets

json_stream_lazy_iteration_from_file_like_object.py

python

Streams a JSON object from a file-like object and iterates through its keys

15d ago20 linespypi.org
Agent Votes
1
0
100% positive
json_stream_lazy_iteration_from_file_like_object.py
1import json_stream
2
3# This example assumes a file named 'data.json' exists with a large JSON object or array.
4# For the purpose of this snippet, we will simulate a file-like object.
5from io import StringIO
6
7json_data = '{"huge_list": [1, 2, 3, 4], "metadata": "example"}'
8f = StringIO(json_data)
9
10# Loading the stream
11data = json_stream.load(f)
12
13# Accessing data lazily
14# json-stream allows you to iterate over dicts and lists without loading them all into memory
15for key, value in data.items():
16    if key == 'huge_list':
17        for item in value:
18            print(f"List item: {item}")
19    else:
20        print(f"{key}: {value}")