0
# JSON Operations
1
2
High-performance JSON serialization and deserialization with comprehensive file I/O support, gzip compression, JSONL format handling, and cross-platform compatibility.
3
4
## Capabilities
5
6
### JSON String Operations
7
8
Core JSON serialization functions for converting between Python objects and JSON strings with optimized performance via ujson.
9
10
```python { .api }
11
def json_dumps(data, indent=0, sort_keys=False):
12
"""
13
Serialize an object to a JSON string.
14
15
Parameters:
16
- data: JSON-serializable Python object
17
- indent (int): Number of spaces for indentation (0 for compact)
18
- sort_keys (bool): Sort dictionary keys (falls back to standard json)
19
20
Returns:
21
str: JSON string representation
22
"""
23
24
def json_loads(data):
25
"""
26
Deserialize JSON string or bytes to Python object.
27
28
Parameters:
29
- data (str | bytes): JSON data to deserialize
30
31
Returns:
32
Any: Deserialized Python object
33
"""
34
```
35
36
### JSON File Operations
37
38
Read and write JSON data to files with automatic encoding handling and support for standard input/output streams.
39
40
```python { .api }
41
def read_json(location):
42
"""
43
Load JSON from file or standard input.
44
45
Parameters:
46
- location (str | Path | "-"): File path or "-" for stdin
47
48
Returns:
49
dict | list: Loaded JSON content
50
51
Raises:
52
ValueError: If file doesn't exist or contains invalid JSON
53
"""
54
55
def write_json(location, data, indent=2):
56
"""
57
Write JSON data to file or standard output.
58
59
Parameters:
60
- location (str | Path | "-"): File path or "-" for stdout
61
- data: JSON-serializable data to write
62
- indent (int): Number of spaces for indentation
63
64
Returns:
65
None
66
"""
67
```
68
69
### Gzipped JSON Operations
70
71
Handle compressed JSON files with automatic gzip compression and decompression.
72
73
```python { .api }
74
def read_gzip_json(location):
75
"""
76
Load JSON from gzipped file.
77
78
Parameters:
79
- location (str | Path): Path to .json.gz file
80
81
Returns:
82
dict | list: Loaded JSON content
83
84
Raises:
85
ValueError: If file doesn't exist or contains invalid JSON
86
"""
87
88
def write_gzip_json(location, data, indent=2):
89
"""
90
Write JSON data to gzipped file.
91
92
Parameters:
93
- location (str | Path): Path for .json.gz file
94
- data: JSON-serializable data to write
95
- indent (int): Number of spaces for indentation
96
97
Returns:
98
None
99
"""
100
```
101
102
### JSONL Operations
103
104
Handle newline-delimited JSON format for streaming large datasets and log files.
105
106
```python { .api }
107
def read_jsonl(location, skip=False):
108
"""
109
Read JSONL file line by line, yielding each JSON object.
110
111
Parameters:
112
- location (str | Path | "-"): File path or "-" for stdin
113
- skip (bool): Skip invalid lines instead of raising error
114
115
Yields:
116
Any: Deserialized JSON object from each line
117
118
Raises:
119
ValueError: If line contains invalid JSON and skip=False
120
"""
121
122
def write_jsonl(location, lines, append=False, append_new_line=True):
123
"""
124
Write iterable of objects as JSONL format.
125
126
Parameters:
127
- location (str | Path | "-"): File path or "-" for stdout
128
- lines (Iterable): JSON-serializable objects to write
129
- append (bool): Append to existing file instead of overwriting
130
- append_new_line (bool): Add newline before appending
131
132
Returns:
133
None
134
"""
135
```
136
137
### JSON Validation
138
139
Utility function to check if objects are JSON-serializable.
140
141
```python { .api }
142
def is_json_serializable(obj):
143
"""
144
Check if a Python object can be serialized to JSON.
145
146
Parameters:
147
- obj: Object to test for JSON compatibility
148
149
Returns:
150
bool: True if object is JSON-serializable, False otherwise
151
"""
152
```
153
154
## Usage Examples
155
156
### Basic JSON Operations
157
158
```python
159
import srsly
160
161
# Serialize to JSON string
162
data = {"users": [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]}
163
json_str = srsly.json_dumps(data, indent=2)
164
print(json_str)
165
166
# Parse JSON string
167
parsed = srsly.json_loads(json_str)
168
print(parsed["users"][0]["name"]) # "Alice"
169
```
170
171
### File I/O with Error Handling
172
173
```python
174
import srsly
175
176
try:
177
# Write to file
178
data = {"config": {"debug": True, "timeout": 30}}
179
srsly.write_json("config.json", data)
180
181
# Read from file
182
loaded_config = srsly.read_json("config.json")
183
print(f"Debug mode: {loaded_config['config']['debug']}")
184
185
except ValueError as e:
186
print(f"JSON error: {e}")
187
```
188
189
### JSONL Processing
190
191
```python
192
import srsly
193
194
# Write log entries
195
log_entries = [
196
{"timestamp": "2023-01-01T12:00:00", "level": "INFO", "message": "Server started"},
197
{"timestamp": "2023-01-01T12:01:00", "level": "ERROR", "message": "Connection failed"}
198
]
199
srsly.write_jsonl("app.log", log_entries)
200
201
# Read and process log entries
202
for entry in srsly.read_jsonl("app.log"):
203
if entry["level"] == "ERROR":
204
print(f"Error at {entry['timestamp']}: {entry['message']}")
205
```
206
207
### Validation and Compatibility
208
209
```python
210
import srsly
211
212
# Check if objects are serializable
213
test_objects = [
214
{"valid": "object"},
215
lambda x: x, # Functions are not serializable
216
[1, 2, 3],
217
set([1, 2, 3]) # Sets are not serializable
218
]
219
220
for obj in test_objects:
221
if srsly.is_json_serializable(obj):
222
json_str = srsly.json_dumps(obj)
223
print(f"Serialized: {json_str}")
224
else:
225
print(f"Cannot serialize: {type(obj)}")
226
```