streamjson 1.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
streamjson/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .streamjsonwriter import StreamJSONWriter
2
+ from .streamjsonreader import StreamJSONReader
@@ -0,0 +1,126 @@
1
+ import json
2
+ from json import JSONDecodeError
3
+ from typing import Any
4
+
5
+
6
+ class StreamJSONReader:
7
+ def __init__(self, file: str, encoding: str = "utf8", **kwds: Any):
8
+ """
9
+ Read objects from a JSON file using a stream. Does not require loading the whole JSON file in memory.
10
+
11
+ :param file: The file
12
+ :param encoding: Determines the encoding
13
+ :param kwds: Arguments for json.loads()
14
+ """
15
+
16
+ self.__file = file
17
+ self.__encoding = encoding
18
+ self.__kwds = kwds
19
+
20
+ self.__reader = self.Reader(
21
+ file=self.__file, encoding=self.__encoding, **self.__kwds
22
+ )
23
+
24
+ def find(self):
25
+ return self.__reader.find()
26
+
27
+ def close(self):
28
+ self.__reader.close()
29
+
30
+ def __enter__(self):
31
+ return self.__reader
32
+
33
+ def __exit__(self, exc_type, exc_val, exc_tb):
34
+ self.__reader.close()
35
+
36
+ class Reader:
37
+ def __init__(self, file: str, encoding: str = "utf8", **kwds: Any):
38
+ """
39
+ :param file: The file
40
+ :param encoding: Determines the encoding
41
+ :param kwds: Arguments for json.loads()
42
+ """
43
+
44
+ self.__file = file
45
+ self.__encoding = encoding
46
+ self.__kwds = kwds
47
+
48
+ self.__opened_file = None
49
+ self.__tmp_lines = ""
50
+ self.__object_is_pending = False
51
+ self.__opening_bracket_index = 0
52
+ self.__size_bytes = 0
53
+
54
+ def find(self):
55
+ """Find JSON object"""
56
+
57
+ # Open the file
58
+ self.__opened_file = open(self.__file, "r", encoding=self.__encoding)
59
+
60
+ # Loop through each line in the JSON file and while doing so, yield JSON objects as they are found
61
+ for line in self.__opened_file:
62
+ # Append new line to tmp_lines
63
+ new_line = "".join(line.splitlines())
64
+ self.__tmp_lines += new_line
65
+
66
+ # FIND OPENING BRACKET {
67
+
68
+ # Not object_is_pending means there is no opening bracket expecting a closing bracket at the moment
69
+ # Therefore it is necessary to look for the opening bracket
70
+ if not self.__object_is_pending:
71
+ # Find the opening bracket and its index
72
+ self.__opening_bracket_index = self.__tmp_lines.find("{", 0)
73
+ # If nothing was found: Clear tmp_lines and continue to try again with the next line from the file
74
+ if self.__opening_bracket_index == -1:
75
+ self.__tmp_lines = ""
76
+ continue
77
+ else:
78
+ # If the opening bracket was found:
79
+ # Set object_is_pending to true meaning a closing bracket is expected next to yield an object
80
+ self.__object_is_pending = True
81
+
82
+ # FIND CLOSING BRACKET }
83
+
84
+ # Get all indices of closing brackets in the string
85
+ closing_brackets_indices = [
86
+ i for i, char in enumerate(self.__tmp_lines) if char == "}"
87
+ ]
88
+
89
+ # Try all closing brackets for possible JSON object completion
90
+ for closing_bracket_index in closing_brackets_indices:
91
+ str_possible_json_object = self.__tmp_lines[
92
+ self.__opening_bracket_index : closing_bracket_index + 1
93
+ ]
94
+ try:
95
+ # Try to load the string as a JSON object
96
+ json_obj = json.loads(s=str_possible_json_object, **self.__kwds)
97
+
98
+ # Clear part of tmp_lines that was used in the object
99
+ self.__tmp_lines = self.__tmp_lines[closing_bracket_index + 1 :]
100
+
101
+ # Set False to start looking for opening bracket next
102
+ self.__object_is_pending = False
103
+
104
+ # Yield the JSON object
105
+ yield json_obj
106
+
107
+ # Append the size of the object
108
+ self.__size_bytes += len(
109
+ str_possible_json_object.encode("utf-8")
110
+ )
111
+
112
+ break
113
+ except JSONDecodeError:
114
+ continue
115
+
116
+ def get_size(self):
117
+ """Get size of total strings successfully converted to JSON objects from file in bytes"""
118
+
119
+ return self.__size_bytes
120
+
121
+ def close(self):
122
+ """Close the reader"""
123
+
124
+ # Close the file
125
+ if self.__opened_file:
126
+ self.__opened_file.close()
@@ -0,0 +1,120 @@
1
+ import json
2
+ import os
3
+
4
+
5
+ class StreamJSONWriter:
6
+ def __init__(self, file: str, indent: int = 2, ensure_ascii: bool = True):
7
+ """
8
+ Write objects or arrays to a JSON file using a stream. Useful for when you don't want to read large amounts of
9
+ data in memory, for example when you need to save large amounts of data from a database to a single JSON file.
10
+
11
+ :param file: The file
12
+ :param indent: Spaces to use at the beginning of line
13
+ :param ensure_ascii: ascii-only json output (replace non-ascii to \\uNNNN), True by default
14
+ """
15
+
16
+ self.__file = file
17
+ self.__indent = indent if indent >= 0 else 0
18
+ self.__ensure_ascii = ensure_ascii
19
+
20
+ self.__writer = self.Writer(self.__file, self.__indent, self.__ensure_ascii)
21
+
22
+ def send(self, value):
23
+ self.__writer.send(value)
24
+
25
+ def close(self):
26
+ self.__writer.close()
27
+
28
+ def __enter__(self):
29
+ return self.__writer
30
+
31
+ def __exit__(self, exc_type, exc_val, exc_tb):
32
+ self.__writer.close()
33
+
34
+ class Writer:
35
+ def __init__(self, file: str, indent: int, ensure_ascii: bool):
36
+ """
37
+ :param file: The file
38
+ :param indent: Spaces to use at the beginning of line
39
+ :param ensure_ascii: ascii-only json output (replace non-ascii to \\uNNNN), True by default
40
+ """
41
+
42
+ self.__file = file
43
+ self.__indent = indent
44
+ self.__stream_started = False
45
+ self.__opened_file = None
46
+ self.__ensure_ascii = ensure_ascii
47
+
48
+ def send(self, value):
49
+ """
50
+ Send value to file
51
+
52
+ :param value: The value to send to the file
53
+ """
54
+
55
+ if not self.__stream_started:
56
+ self.__stream_started = True
57
+
58
+ # Remove the file before writing to it
59
+ if os.path.exists(self.__file):
60
+ os.remove(self.__file)
61
+
62
+ # Open the file
63
+ self.__opened_file = open(self.__file, "a")
64
+
65
+ # Add opening bracket at first write
66
+ self.__opened_file.write("[")
67
+
68
+ # Create JSON string from value
69
+ json_value = json.dumps(
70
+ json.loads(json.dumps(value, ensure_ascii=self.__ensure_ascii)),
71
+ indent=self.__indent,
72
+ ensure_ascii=self.__ensure_ascii,
73
+ )
74
+
75
+ # Indent the whole value
76
+ json_value_indented = self.__indent_string(json_value)
77
+
78
+ self.__opened_file.write(f"\n{json_value_indented},")
79
+
80
+ def __indent_string(self, string) -> str:
81
+ """
82
+ Indent a string
83
+
84
+ :param string: String to indent
85
+ :return: The indented string
86
+ """
87
+
88
+ def get_indent() -> str:
89
+ """String representing the indentation"""
90
+
91
+ indent_string = ""
92
+ for x in range(self.__indent):
93
+ indent_string += " "
94
+ return indent_string
95
+
96
+ indent = get_indent()
97
+ return indent + string.replace("\n", "\n" + indent)
98
+
99
+ def __remove_last_comma(self, file):
100
+ """
101
+ Remove the last comma from the file
102
+
103
+ :param file: The file
104
+ """
105
+
106
+ file.seek(file.tell() - 1, os.SEEK_SET)
107
+ file.truncate()
108
+
109
+ def close(self):
110
+ """Close the writer"""
111
+
112
+ if self.__stream_started and self.__opened_file:
113
+ # Remove last comma
114
+ self.__remove_last_comma(self.__opened_file)
115
+
116
+ # Add the closing bracket
117
+ self.__opened_file.write("\n]")
118
+
119
+ # Close the file
120
+ self.__opened_file.close()
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: streamjson
3
+ Version: 1.0.3
4
+ Summary: Send objects or arrays to a JSON file using a stream. Read objects from a JSON file using a stream.
5
+ Author-email: Zairon Jacobs <zaironjacobs@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: homepage, https://github.com/zaironjacobs/streamjson
8
+ Project-URL: download, https://github.com/zaironjacobs/streamjson/archive/v1.0.3.tar.gz
9
+ Keywords: json,stream,write,file,read,objects,arrays
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Natural Language :: English
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # StreamJSON
24
+
25
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/streamjson?color=blue)](https://pypi.python.org/pypi/streamjson)
26
+ [![PyPI](https://img.shields.io/pypi/v/streamjson?color=blue)](https://pypi.python.org/pypi/streamjson)
27
+ [![PyPI - License](https://img.shields.io/pypi/l/streamjson)](https://pypi.python.org/pypi/streamjson)
28
+
29
+ [![tests](https://github.com/zaironjacobs/streamjson/actions/workflows/test.yml/badge.svg)](https://github.com/zaironjacobs/streamjson/actions/workflows/test.yml)
30
+
31
+ Write objects or arrays to a JSON file using a stream. Useful for when you don't want to read large amounts of data in
32
+ memory, for example when you need to save large amounts of data from a database to a single JSON file.
33
+
34
+ Read objects from a JSON file using a stream. Does not require loading the whole JSON file in memory.
35
+
36
+ ## Install
37
+
38
+ ```console
39
+ pip install streamjson
40
+ ```
41
+
42
+ ## How to write to JSON file
43
+
44
+ Fetch data from a database or anywhere else and send to a JSON file. The send function takes in a dictionary or a list.
45
+ A new file with the given name will be created, the root of the JSON file is an array by default.
46
+
47
+ ```Python
48
+ from streamjson import StreamJSONWriter
49
+
50
+ persons = [{'id': '0001', 'first_name': 'John', 'last_name': 'Doe'},
51
+ {'id': '0002', 'first_name': 'Jane', 'last_name': 'Doe'}]
52
+
53
+ with StreamJSONWriter('persons.json', indent=2) as writer:
54
+ for person in persons:
55
+ writer.send(person)
56
+ ```
57
+
58
+ persons.json:
59
+
60
+ ```JSON
61
+ [
62
+ {
63
+ "id": "0001",
64
+ "first_name": "John",
65
+ "last_name": "Doe"
66
+ },
67
+ {
68
+ "id": "0002",
69
+ "first_name": "Jane",
70
+ "last_name": "Doe"
71
+ }
72
+ ]
73
+ ```
74
+
75
+ ## How to read from JSON file
76
+
77
+ The reader will stream each object from the JSON file.
78
+
79
+ ```Python
80
+ from streamjson import StreamJSONReader
81
+
82
+ with StreamJSONReader('persons.json') as reader:
83
+ for obj in reader.find():
84
+ print(obj)
85
+ ```
@@ -0,0 +1,10 @@
1
+ streamjson/__init__.py,sha256=cIqhs_MmO8BF3C-0tEyayiN-J7GW67wA_GyzFNPHZ6I,94
2
+ streamjson/streamjsonreader.py,sha256=_G-TnSgSzqxOrCp-vcYd-9LglxIrsjqtRP1jt9lgoSY,4656
3
+ streamjson/streamjsonwriter.py,sha256=yT6PmCcJANxyYoO7feueHg5Zn33XOKSjGPQhhxY4Dgg,3764
4
+ streamjson-1.0.3.dist-info/licenses/LICENSE,sha256=onT5tOHU-R33_0QLoCcrxyMIc9pPUCEQMYKrc5jSx-A,1069
5
+ tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ tests/test_app.py,sha256=i02yFR0EwnTeqDqYK6l2RjU3zU2_im8qAJk3RRiXGy4,1742
7
+ streamjson-1.0.3.dist-info/METADATA,sha256=vfIElroe27BCThK6KuFbYUHhO7_5UaceWbMWdE6LUkU,2821
8
+ streamjson-1.0.3.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ streamjson-1.0.3.dist-info/top_level.txt,sha256=_nCeM-g6_juctn1iAfz9vGbuKPFrqB-VH85dI5uHlRU,17
10
+ streamjson-1.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zairon Jacobs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ streamjson
2
+ tests
tests/__init__.py ADDED
File without changes
tests/test_app.py ADDED
@@ -0,0 +1,59 @@
1
+ import os
2
+ import json
3
+
4
+ import pytest
5
+
6
+ from streamjson import StreamJSONWriter, StreamJSONReader
7
+
8
+ tmp_json_file = os.path.join(os.path.dirname(__file__), "test.json")
9
+
10
+
11
+ class TestStreamJSON:
12
+ def test_writer_send(self):
13
+ persons = [
14
+ {"id": "0001", "first_name": "John", "last_name": "Doe"},
15
+ {"id": "0002", "first_name": "Jane", "last_name": "Doe"},
16
+ ]
17
+
18
+ with StreamJSONWriter(tmp_json_file, indent=2) as writer:
19
+ for person in persons:
20
+ writer.send(person)
21
+
22
+ with open(tmp_json_file, "r") as file:
23
+ expected = persons
24
+ result = json.load(file)
25
+
26
+ assert expected == result
27
+
28
+ def test_reader_find(self):
29
+ persons_json_file = os.path.join(os.path.dirname(__file__), "persons.json")
30
+ with StreamJSONReader(persons_json_file) as reader:
31
+ reader_generator = reader.find()
32
+ obj_1 = next(reader_generator)
33
+ obj_2 = next(reader_generator)
34
+
35
+ assert obj_1 == {
36
+ "id": "0001",
37
+ "first_name": "John",
38
+ "last_name": "Doe",
39
+ "hobbies": [
40
+ {"name": "photography"},
41
+ {"name": "programming"},
42
+ {"name": "hiking"},
43
+ ],
44
+ } and obj_2 == {
45
+ "id": "0002",
46
+ "first_name": "Jane",
47
+ "last_name": "Doe",
48
+ "hobbies": [{"name": "dancing"}],
49
+ }
50
+
51
+ @pytest.fixture(scope="session", autouse=True)
52
+ def cleanup(self):
53
+ """
54
+ Delete file after tests are finished.
55
+ """
56
+
57
+ yield
58
+ if os.path.exists(tmp_json_file):
59
+ os.remove(tmp_json_file)