json-structure 0.1.6__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.
@@ -0,0 +1,373 @@
1
+ """
2
+ JSON Source Locator - Maps JSON Pointer paths to line/column positions.
3
+ """
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional, Tuple, Union
7
+ from .error_codes import JsonLocation
8
+
9
+
10
+ class JsonSourceLocator:
11
+ """
12
+ Tracks line and column positions in a JSON document and maps
13
+ JSON Pointer paths to source locations.
14
+ """
15
+
16
+ def __init__(self, json_text: str):
17
+ """
18
+ Initialize the source locator with the JSON text.
19
+
20
+ Args:
21
+ json_text: The raw JSON text to analyze
22
+ """
23
+ self._json_text = json_text
24
+ self._line_offsets = self._build_line_offsets(json_text)
25
+
26
+ def _build_line_offsets(self, text: str) -> List[int]:
27
+ """
28
+ Build an array of line start offsets for efficient line/column lookup.
29
+
30
+ Args:
31
+ text: The text to analyze
32
+
33
+ Returns:
34
+ List of character offsets where each line starts
35
+ """
36
+ offsets = [0] # First line starts at offset 0
37
+ for i, char in enumerate(text):
38
+ if char == '\n':
39
+ offsets.append(i + 1)
40
+ return offsets
41
+
42
+ def _offset_to_location(self, offset: int) -> JsonLocation:
43
+ """
44
+ Convert a character offset to line/column position.
45
+
46
+ Args:
47
+ offset: Character offset in the text
48
+
49
+ Returns:
50
+ JsonLocation with line and column (1-based)
51
+ """
52
+ if offset < 0 or offset > len(self._json_text):
53
+ return JsonLocation.unknown()
54
+
55
+ # Binary search for the line
56
+ line = 0
57
+ left, right = 0, len(self._line_offsets) - 1
58
+ while left <= right:
59
+ mid = (left + right) // 2
60
+ if self._line_offsets[mid] <= offset:
61
+ line = mid
62
+ left = mid + 1
63
+ else:
64
+ right = mid - 1
65
+
66
+ # Column is offset from line start (1-based)
67
+ column = offset - self._line_offsets[line] + 1
68
+ return JsonLocation(line + 1, column) # 1-based line numbers
69
+
70
+ def get_location(self, path: str, parsed_json: Any = None) -> JsonLocation:
71
+ """
72
+ Get the source location for a JSON Pointer path.
73
+
74
+ Args:
75
+ path: JSON Pointer path (e.g., "/properties/name" or "#/properties/name")
76
+ parsed_json: Optional parsed JSON object (not used in text-based location)
77
+
78
+ Returns:
79
+ JsonLocation for the path, or unknown location if not found
80
+ """
81
+ if not path or not self._json_text:
82
+ return JsonLocation.unknown()
83
+
84
+ # Parse the JSON Pointer path
85
+ segments = self._parse_json_pointer(path)
86
+
87
+ # Navigate through the JSON text to find the location
88
+ return self._find_location_in_text(segments)
89
+
90
+ def _parse_json_pointer(self, path: str) -> List[str]:
91
+ """
92
+ Parse a JSON Pointer path into segments.
93
+
94
+ Args:
95
+ path: JSON Pointer path (e.g., "/properties/name" or "#/properties/name")
96
+
97
+ Returns:
98
+ List of path segments
99
+ """
100
+ # Remove leading # if present (JSON Pointer fragment identifier)
101
+ if path.startswith('#'):
102
+ path = path[1:]
103
+
104
+ # Handle empty path or just "/"
105
+ if not path or path == '/':
106
+ return []
107
+
108
+ # Split by / and unescape segments
109
+ segments = []
110
+ for segment in path.split('/'):
111
+ if not segment:
112
+ continue
113
+ # Unescape JSON Pointer tokens
114
+ segment = segment.replace('~1', '/').replace('~0', '~')
115
+ segments.append(segment)
116
+
117
+ return segments
118
+
119
+ def _find_location_in_text(self, segments: List[str]) -> JsonLocation:
120
+ """
121
+ Navigate through JSON text to find the location of a path.
122
+
123
+ Args:
124
+ segments: Path segments to navigate
125
+
126
+ Returns:
127
+ JsonLocation for the path
128
+ """
129
+ text = self._json_text
130
+ offset = 0
131
+
132
+ # Skip initial whitespace
133
+ offset = self._skip_whitespace(text, offset)
134
+
135
+ if offset >= len(text):
136
+ return JsonLocation.unknown()
137
+
138
+ # If no segments, return the start of the document
139
+ if not segments:
140
+ return self._offset_to_location(offset)
141
+
142
+ # Navigate through each segment
143
+ for i, segment in enumerate(segments):
144
+ offset = self._skip_whitespace(text, offset)
145
+
146
+ if offset >= len(text):
147
+ return JsonLocation.unknown()
148
+
149
+ char = text[offset]
150
+
151
+ if char == '{':
152
+ # Object - find the property
153
+ offset = self._find_object_property(text, offset, segment)
154
+ if offset < 0:
155
+ return JsonLocation.unknown()
156
+ elif char == '[':
157
+ # Array - find the index
158
+ try:
159
+ index = int(segment)
160
+ offset = self._find_array_element(text, offset, index)
161
+ if offset < 0:
162
+ return JsonLocation.unknown()
163
+ except ValueError:
164
+ return JsonLocation.unknown()
165
+ else:
166
+ # Not an object or array, can't navigate further
167
+ return JsonLocation.unknown()
168
+
169
+ return self._offset_to_location(offset)
170
+
171
+ def _skip_whitespace(self, text: str, offset: int) -> int:
172
+ """Skip whitespace characters."""
173
+ while offset < len(text) and text[offset] in ' \t\n\r':
174
+ offset += 1
175
+ return offset
176
+
177
+ def _skip_string(self, text: str, offset: int) -> int:
178
+ """Skip a JSON string value and return the offset after the closing quote."""
179
+ if offset >= len(text) or text[offset] != '"':
180
+ return offset
181
+
182
+ offset += 1 # Skip opening quote
183
+ while offset < len(text):
184
+ char = text[offset]
185
+ if char == '\\':
186
+ offset += 2 # Skip escape sequence
187
+ elif char == '"':
188
+ return offset + 1 # Return position after closing quote
189
+ else:
190
+ offset += 1
191
+ return offset
192
+
193
+ def _skip_value(self, text: str, offset: int) -> int:
194
+ """Skip a JSON value and return the offset after it."""
195
+ offset = self._skip_whitespace(text, offset)
196
+
197
+ if offset >= len(text):
198
+ return offset
199
+
200
+ char = text[offset]
201
+
202
+ if char == '"':
203
+ return self._skip_string(text, offset)
204
+ elif char == '{':
205
+ return self._skip_object(text, offset)
206
+ elif char == '[':
207
+ return self._skip_array(text, offset)
208
+ elif char in 'tfn':
209
+ # true, false, null
210
+ for keyword in ['true', 'false', 'null']:
211
+ if text[offset:offset+len(keyword)] == keyword:
212
+ return offset + len(keyword)
213
+ return offset
214
+ elif char in '-0123456789':
215
+ # Number
216
+ while offset < len(text) and text[offset] in '-+.0123456789eE':
217
+ offset += 1
218
+ return offset
219
+
220
+ return offset
221
+
222
+ def _skip_object(self, text: str, offset: int) -> int:
223
+ """Skip an entire JSON object."""
224
+ if offset >= len(text) or text[offset] != '{':
225
+ return offset
226
+
227
+ offset += 1 # Skip opening brace
228
+ depth = 1
229
+
230
+ while offset < len(text) and depth > 0:
231
+ offset = self._skip_whitespace(text, offset)
232
+ if offset >= len(text):
233
+ break
234
+
235
+ char = text[offset]
236
+ if char == '{':
237
+ depth += 1
238
+ offset += 1
239
+ elif char == '}':
240
+ depth -= 1
241
+ offset += 1
242
+ elif char == '"':
243
+ offset = self._skip_string(text, offset)
244
+ else:
245
+ offset += 1
246
+
247
+ return offset
248
+
249
+ def _skip_array(self, text: str, offset: int) -> int:
250
+ """Skip an entire JSON array."""
251
+ if offset >= len(text) or text[offset] != '[':
252
+ return offset
253
+
254
+ offset += 1 # Skip opening bracket
255
+ depth = 1
256
+
257
+ while offset < len(text) and depth > 0:
258
+ offset = self._skip_whitespace(text, offset)
259
+ if offset >= len(text):
260
+ break
261
+
262
+ char = text[offset]
263
+ if char == '[':
264
+ depth += 1
265
+ offset += 1
266
+ elif char == ']':
267
+ depth -= 1
268
+ offset += 1
269
+ elif char == '{':
270
+ offset = self._skip_object(text, offset)
271
+ elif char == '"':
272
+ offset = self._skip_string(text, offset)
273
+ else:
274
+ offset += 1
275
+
276
+ return offset
277
+
278
+ def _find_object_property(self, text: str, offset: int, property_name: str) -> int:
279
+ """
280
+ Find a property in an object and return the offset of its value.
281
+
282
+ Args:
283
+ text: JSON text
284
+ offset: Starting offset (should be at the opening brace)
285
+ property_name: Name of the property to find
286
+
287
+ Returns:
288
+ Offset of the property value, or -1 if not found
289
+ """
290
+ if offset >= len(text) or text[offset] != '{':
291
+ return -1
292
+
293
+ offset += 1 # Skip opening brace
294
+
295
+ while offset < len(text):
296
+ offset = self._skip_whitespace(text, offset)
297
+
298
+ if offset >= len(text):
299
+ return -1
300
+
301
+ if text[offset] == '}':
302
+ return -1 # End of object, property not found
303
+
304
+ # Skip comma if present
305
+ if text[offset] == ',':
306
+ offset += 1
307
+ offset = self._skip_whitespace(text, offset)
308
+
309
+ # Expect a property name (string)
310
+ if offset >= len(text) or text[offset] != '"':
311
+ return -1
312
+
313
+ # Parse the property name
314
+ name_start = offset + 1
315
+ offset = self._skip_string(text, offset)
316
+ name_end = offset - 1 # Don't include closing quote
317
+ current_name = text[name_start:name_end]
318
+
319
+ # Skip whitespace and colon
320
+ offset = self._skip_whitespace(text, offset)
321
+ if offset >= len(text) or text[offset] != ':':
322
+ return -1
323
+ offset += 1
324
+ offset = self._skip_whitespace(text, offset)
325
+
326
+ if current_name == property_name:
327
+ return offset # Return offset of the value
328
+
329
+ # Skip this value
330
+ offset = self._skip_value(text, offset)
331
+
332
+ return -1
333
+
334
+ def _find_array_element(self, text: str, offset: int, index: int) -> int:
335
+ """
336
+ Find an array element by index and return the offset of its value.
337
+
338
+ Args:
339
+ text: JSON text
340
+ offset: Starting offset (should be at the opening bracket)
341
+ index: Array index to find
342
+
343
+ Returns:
344
+ Offset of the element value, or -1 if not found
345
+ """
346
+ if offset >= len(text) or text[offset] != '[':
347
+ return -1
348
+
349
+ offset += 1 # Skip opening bracket
350
+ current_index = 0
351
+
352
+ while offset < len(text):
353
+ offset = self._skip_whitespace(text, offset)
354
+
355
+ if offset >= len(text):
356
+ return -1
357
+
358
+ if text[offset] == ']':
359
+ return -1 # End of array, index not found
360
+
361
+ # Skip comma if present
362
+ if text[offset] == ',':
363
+ offset += 1
364
+ offset = self._skip_whitespace(text, offset)
365
+
366
+ if current_index == index:
367
+ return offset # Return offset of the element
368
+
369
+ # Skip this value
370
+ offset = self._skip_value(text, offset)
371
+ current_index += 1
372
+
373
+ return -1