Update data_extraction.py
Browse files- data_extraction.py +23 -0
data_extraction.py
CHANGED
|
@@ -89,6 +89,27 @@ def _context_snippet(raw, pos, window=120):
|
|
| 89 |
return f"...{before!r} <-- ERROR HERE --> {after!r}..."
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def load_records(filepaths):
|
| 93 |
"""
|
| 94 |
Handles several shapes robustly:
|
|
@@ -108,6 +129,8 @@ def load_records(filepaths):
|
|
| 108 |
print(f" [skip] {fp} is empty")
|
| 109 |
continue
|
| 110 |
|
|
|
|
|
|
|
| 111 |
whole_file_error = None
|
| 112 |
try:
|
| 113 |
obj = json.loads(raw)
|
|
|
|
| 89 |
return f"...{before!r} <-- ERROR HERE --> {after!r}..."
|
| 90 |
|
| 91 |
|
| 92 |
+
def _preprocess_mongo_shell_syntax(raw):
|
| 93 |
+
"""
|
| 94 |
+
Converts MongoDB *shell* export syntax into plain JSON.
|
| 95 |
+
mongoexport/mongodump produce valid JSON (e.g. {"$oid": "..."}), but a
|
| 96 |
+
raw copy-paste from the mongo shell or Compass often contains
|
| 97 |
+
constructor-style tokens that are NOT valid JSON, e.g.:
|
| 98 |
+
ObjectId("665f1...") -> "665f1..."
|
| 99 |
+
ISODate("2024-01-01T00:00:00Z") -> "2024-01-01T00:00:00Z"
|
| 100 |
+
NumberLong(123) -> 123
|
| 101 |
+
NumberInt(123) -> 123
|
| 102 |
+
NumberDecimal("1.5") -> "1.5"
|
| 103 |
+
Timestamp(123, 1) -> "Timestamp(123, 1)" (rare; kept as string)
|
| 104 |
+
This rewrites those into equivalent plain JSON values.
|
| 105 |
+
"""
|
| 106 |
+
# ObjectId("...") / ISODate("...") / NumberDecimal("...") -> just the quoted string
|
| 107 |
+
raw = re.sub(r'\b(?:ObjectId|ISODate|NumberDecimal|UUID)\(\s*"([^"]*)"\s*\)', r'"\1"', raw)
|
| 108 |
+
# NumberLong(123) / NumberInt(123) -> bare number (handles quoted numbers too)
|
| 109 |
+
raw = re.sub(r'\b(?:NumberLong|NumberInt)\(\s*"?(-?\d+)"?\s*\)', r'\1', raw)
|
| 110 |
+
return raw
|
| 111 |
+
|
| 112 |
+
|
| 113 |
def load_records(filepaths):
|
| 114 |
"""
|
| 115 |
Handles several shapes robustly:
|
|
|
|
| 129 |
print(f" [skip] {fp} is empty")
|
| 130 |
continue
|
| 131 |
|
| 132 |
+
raw = _preprocess_mongo_shell_syntax(raw)
|
| 133 |
+
|
| 134 |
whole_file_error = None
|
| 135 |
try:
|
| 136 |
obj = json.loads(raw)
|