### Untitled No description -------------------------------- ### Python Virtual Environment Setup Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Instructions on setting up a virtual environment for developing the json_repair library using requirements.txt and pre-commit hooks. ```bash create a virtual environment with requirements.txt ``` -------------------------------- ### Install json_repair CLI Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Provides the command to install the json_repair library for command-line interface usage. This enables repairing and parsing JSON files directly from the terminal. ```bash pipx install json-repair ``` -------------------------------- ### Untitled No description -------------------------------- ### Repair Broken JSON from Standard Input Source: https://context7.com/mangiucugna/json_repair/llms.txt This example demonstrates repairing broken JSON data piped from standard input. It shows how to handle incomplete JSON structures and produces a valid JSON output. ```bash echo '{"name": "Alice", "items": ["a", "b"' | json_repair ``` -------------------------------- ### Untitled No description -------------------------------- ### JSON Repair using CLI Tool Source: https://context7.com/mangiucugna/json_repair/llms.txt Provides a command-line interface (CLI) tool for repairing JSON files or standard input. It allows for inline file replacement, redirection of output to a new file, and supports various formatting options. Installation is typically done via `pipx`. ```bash # Install for CLI usage pipx install json-repair # Repair file and print to stdout json_repair broken.json # Read from stdin cat broken.json | json_repair # Replace file inline json_repair -i broken.json # Write to different file json_repair broken.json -o fixed.json ``` -------------------------------- ### Untitled No description -------------------------------- ### Pass json.dumps Parameters via repair_json in Python Source: https://github.com/mangiucugna/json_repair/blob/main/README.md The `repair_json` function in this library is designed to accept and pass through all parameters that the standard Python `json.dumps()` function accepts. This allows for flexible formatting of the repaired JSON string, such as specifying indentation levels. The example demonstrates passing the `indent` parameter. ```python from json_repair import repair_json bad_json_string = "{'key': 'value', 'nested': {'a': 1}}" # Repair and pretty-print the JSON string with an indent of 4 spaces repaired_and_indented_json = repair_json(bad_json_string, indent=4) print(repaired_and_indented_json) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### JSON Repair CLI Help Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Displays the help message for the json_repair command-line tool, showing available arguments and options for file repair and parsing. ```bash $ json_repair -h usage: json_repair [-h] [-i] [-o TARGET] [--ensure_ascii] [--indent INDENT] [filename] Repair and parse JSON files. positional arguments: filename The JSON file to repair (if omitted, reads from stdin) options: -h, --help show this help message and exit -i, --inline Replace the file inline instead of returning the output to stdout -o TARGET, --output TARGET If specified, the output will be written to TARGET filename instead of stdout --ensure_ascii Pass ensure_ascii=True to json.dumps() --indent INDENT Number of spaces for indentation (Default 2) ``` -------------------------------- ### Python Build Process Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Command to build the Python package for the json_repair library using the 'build' module. ```python python -m build ``` -------------------------------- ### Load and Repair JSON with Options in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt This Python snippet illustrates using `json_repair.loads` with options like `return_objects=True` for performance and `skip_json_loads=True` when input is known to be invalid. ```python import json_repair broken_json_string = '{"name": "Alice", "items": ["a", "b"' repaired_data = json_repair.loads(broken_json_string, return_objects=True, skip_json_loads=True) print(repaired_data) ``` -------------------------------- ### Untitled No description -------------------------------- ### CLI - Command-line JSON repair tool Source: https://context7.com/mangiucugna/json_repair/llms.txt Provides a command-line interface for repairing JSON files or stdin input. Supports inline replacement, output redirection, and formatting options. ```APIDOC ## CLI - Command-line JSON repair tool ### Description Command-line interface for repairing JSON files or stdin input. Supports inline replacement, output redirection, and formatting options. ### Usage 1. **Install for CLI usage:** ```bash pipx install json-repair ``` 2. **Repair file and print to stdout:** ```bash json_repair broken.json ``` 3. **Read from stdin:** ```bash cat broken.json | json_repair ``` 4. **Replace file inline:** ```bash json_repair -i broken.json ``` 5. **Write to different file:** ```bash json_repair broken.json -o fixed.json ``` ### Parameters - `broken.json`: The path to the JSON file to repair. - `-i` or `--inline`: Replace the original file with the repaired content. - `-o` or `--output`: Specify an output file path for the repaired JSON. ### Example ```bash # Repair a file and save the output to a new file json_repair input.json -o output.json # Repair JSON from standard input and overwrite the original file (use with caution) cat data.json | json_repair -i ``` ``` -------------------------------- ### Load and Repair JSON File in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt This Python snippet demonstrates repairing JSON data directly from a file using `json_repair.load`. It offers a convenient way to handle malformed JSON files. ```python import json_repair with open('broken.json', 'r') as f: repaired_data = json_repair.load(f) print(repaired_data) ``` -------------------------------- ### Add json_repair to requirements.txt Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Illustrates how to pin the json_repair library to a major version in a Python project's requirements.txt file, ensuring compatibility with minor and patch updates. ```python json_repair==0.* ``` -------------------------------- ### Repair JSON with Custom Indentation Source: https://context7.com/mangiucugna/json_repair/llms.txt This command-line usage demonstrates how to repair a JSON file and apply custom indentation to the output. It's useful for formatting repaired JSON for readability. ```bash json_repair broken.json --indent 4 ``` -------------------------------- ### Untitled No description -------------------------------- ### Repair JSON with Skipping json.loads Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Demonstrates how to repair a JSON string while skipping the initial json.loads() call for potential performance gains. This is useful when you are certain the input string is not valid JSON. ```python from json_repair import repair_json good_json_string = repair_json(bad_json_string, skip_json_loads=True) ``` -------------------------------- ### Repair JSON with Streaming Input Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Shows how to use the json_repair library to repair JSON data that is being streamed. This is achieved by setting the `stream_stable` parameter to True. ```python stream_output = repair_json(stream_input, stream_stable=True) ``` -------------------------------- ### from_file() - Load JSON directly from filename Source: https://context7.com/mangiucugna/json_repair/llms.txt Convenience function that opens a file and repairs its JSON content, returning a Python object. Handles file operations internally with proper resource management. ```APIDOC ## from_file() ### Description Convenience function that opens a file and repairs its JSON content, returning a Python object. Handles file operations internally with proper resource management. ### Method `from_file(filename, chunk_length=1048576, skip_json_loads=False, logging=False, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters - **filename** (str) - Required - The path to the JSON file. - **chunk_length** (int) - Optional - The size of chunks to read for large files. Defaults to 1MB. - **skip_json_loads** (bool) - Optional - If True, skips the initial `json.loads()` validation for performance. Defaults to False. - **logging** (bool) - Optional - If True, returns a tuple of (parsed_object, repair_log). Defaults to False. - **kwargs** - Optional - Any keyword arguments accepted by `json.dumps()` for output formatting. ### Request Example ```python from json_repair import from_file # Simple file loading data = from_file('config.json') # Handle IO exceptions yourself try: data = from_file('/path/to/data.json') except (OSError, IOError) as e: print(f"Failed to read file: {e}") # Large files with chunked reading data = from_file('large_dataset.json', chunk_length=2097152) # 2MB chunks # Get repair information data, log = from_file('data.json', logging=True) for entry in log: print(f"Repair: {entry['text']} at {entry['context']}") ``` ### Response #### Success Response (200) - **parsed_object** (dict or list) - The parsed Python object from the repaired JSON. - **repair_log** (list) - A list of repair actions performed, if `logging=True`. #### Response Example ```json { "setting": "value" } ``` ``` -------------------------------- ### load() - Drop-in replacement for json.load() Source: https://context7.com/mangiucugna/json_repair/llms.txt Reads and repairs JSON from a file descriptor, returning a Python object. Supports chunked reading for large files with configurable chunk size. ```APIDOC ## load() ### Description Reads and repairs JSON from a file descriptor, returning a Python object. Supports chunked reading for large files with configurable chunk size. ### Method `load(file_descriptor, chunk_length=1048576, skip_json_loads=False, logging=False, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters - **file_descriptor** (file object) - Required - The file descriptor to read from. - **chunk_length** (int) - Optional - The size of chunks to read for large files. Defaults to 1MB. - **skip_json_loads** (bool) - Optional - If True, skips the initial `json.loads()` validation for performance. Defaults to False. - **logging** (bool) - Optional - If True, returns a tuple of (parsed_object, repair_log). Defaults to False. - **kwargs** - Optional - Any keyword arguments accepted by `json.dumps()` for output formatting. ### Request Example ```python import json_repair # Read from file descriptor with open('data.json', 'r') as fd: data = json_repair.load(fd) # Handle broken JSON files with open('broken.json', 'r') as fd: data = json_repair.load(fd) # Automatically repairs: missing brackets, quotes, commas, etc. # Large file with custom chunk size (1MB chunks) with open('large.json', 'r') as fd: data = json_repair.load(fd, chunk_length=1048576) # Get repair log with open('data.json', 'r') as fd: data, log = json_repair.load(fd, logging=True) # Skip validation for performance with open('data.json', 'r') as fd: data = json_repair.load(fd, skip_json_loads=True) ``` ### Response #### Success Response (200) - **parsed_object** (dict or list) - The parsed Python object from the repaired JSON. - **repair_log** (list) - A list of repair actions performed, if `logging=True`. #### Response Example ```json { "key": "value" } ``` ``` -------------------------------- ### repair_json() - Fix and return JSON string Source: https://context7.com/mangiucugna/json_repair/llms.txt Repairs a malformed JSON string and returns either a valid JSON string or Python object. It first tries standard `json.loads()` and applies repair logic only if parsing fails. Supports `json.dumps()` parameters for output formatting. ```APIDOC ## repair_json() ### Description Repairs a malformed JSON string and returns either a valid JSON string or Python object. Supports all `json.dumps()` parameters for output formatting. ### Method `repair_json(json_string, return_objects=False, skip_json_loads=False, logging=False, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters - **json_string** (str) - Required - The malformed JSON string to repair. - **return_objects** (bool) - Optional - If True, returns a Python object instead of a JSON string. Defaults to False. - **skip_json_loads** (bool) - Optional - If True, skips the initial `json.loads()` validation for performance. Defaults to False. - **logging** (bool) - Optional - If True, returns a tuple of (repaired_data, repair_log). Defaults to False. - **kwargs** - Optional - Any keyword arguments accepted by `json.dumps()` for output formatting. ### Request Example ```python from json_repair import repair_json # Basic repair - missing closing brace broken_json = '{"name": "John", "age": 30' fixed = repair_json(broken_json) # Returns: '{"name": "John", "age": 30}' # Return Python object instead of string result = repair_json('{"key": "value"', return_objects=True) # Returns: {'key': 'value'} # Preserve non-Latin characters chinese = "{'test': '统一码'}" fixed = repair_json(chinese, ensure_ascii=False) # Returns: "{\"test\": \"统一码\"}" # Get repair log for debugging result, log = repair_json('{"broken": json}', return_objects=True, logging=True) # Returns: ({'broken': 'json'}, [{'text': '...', 'context': '...'}]) # Skip json.loads validation for performance fixed = repair_json(known_broken_json, skip_json_loads=True) # Streaming JSON repair stream_output = repair_json(streaming_input, stream_stable=True) ``` ### Response #### Success Response (200) - **repaired_json** (str or dict/list) - The repaired JSON string or Python object. - **repair_log** (list) - A list of repair actions performed, if `logging=True`. #### Response Example ```json { "name": "John", "age": 30 } ``` ``` -------------------------------- ### JSON Repair BNF Definition Source: https://github.com/mangiucugna/json_repair/blob/main/README.md Presents the Backus-Naur Form (BNF) definition for JSON, illustrating the structure of valid JSON documents including primitives and containers. ```bnf ::= | ::= | | ; Where: ; is a valid real number expressed in one of a number of given formats ; is a string of valid characters enclosed in quotes ; is one of the literal strings 'true', 'false', or 'null' (unquoted) ::= | ::= '[' [ *(', ' ) ] ']' ; A sequence of JSON values separated by commas ::= '{' [ *(', ' ) ] '}' ; A sequence of 'members' ::= ': ' ; A pair consisting of a name, and a JSON value ``` -------------------------------- ### Load and Repair JSON Data in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt This Python snippet shows how to use the `json_repair` library to load and repair JSON data from a string. It replaces the standard `json.loads` with `json_repair.loads` for automatic error correction. ```python import json_repair broken_json_string = '{"name": "Alice", "items": ["a", "b"' repaired_data = json_repair.loads(broken_json_string) print(repaired_data) ``` -------------------------------- ### Repair JSON String with Python Source: https://context7.com/mangiucugna/json_repair/llms.txt Fixes a malformed JSON string and returns either a valid JSON string or a Python object. It attempts standard parsing first and applies repair logic only if necessary. Supports `json.dumps()` parameters for output formatting and can return a repair log. ```python from json_repair import repair_json # Basic repair - missing closing brace broken_json = '{"name": "John", "age": 30' fixed = repair_json(broken_json) # Returns: '{"name": "John", "age": 30}' # Return Python object instead of string result = repair_json('{"key": "value"', return_objects=True) # Returns: {'key': 'value'} # Preserve non-Latin characters chinese = "{'test': '统一码'}" fixed = repair_json(chinese, ensure_ascii=False) # Returns: {"test": "统一码"} # Get repair log for debugging result, log = repair_json('{"broken": json}', return_objects=True, logging=True) # Returns: ({'broken': 'json'}, [{'text': '...', 'context': '...'}]) # Skip json.loads validation for performance fixed = repair_json(known_broken_json, skip_json_loads=True) # Streaming JSON repair stream_output = repair_json(streaming_input, stream_stable=True) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Repair JSON and Ensure Non-ASCII Characters Preservation Source: https://context7.com/mangiucugna/json_repair/llms.txt This command-line usage shows how to repair a JSON file while ensuring that non-ASCII characters are preserved in their original form. This is important for internationalized data. ```bash json_repair data.json --ensure_ascii ``` -------------------------------- ### Untitled No description -------------------------------- ### loads() - Drop-in replacement for json.loads() Source: https://context7.com/mangiucugna/json_repair/llms.txt Parses a JSON string and returns a Python object, automatically repairing malformed JSON. This function is a convenience wrapper around `repair_json()` with `return_objects=True`. ```APIDOC ## loads() ### Description Parses a JSON string and returns a Python object, automatically repairing malformed JSON. This function is a convenience wrapper around `repair_json()` with `return_objects=True`. ### Method `loads(json_string, skip_json_loads=False, logging=False, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters - **json_string** (str) - Required - The malformed JSON string to parse. - **skip_json_loads** (bool) - Optional - If True, skips the initial `json.loads()` validation for performance. Defaults to False. - **logging** (bool) - Optional - If True, returns a tuple of (parsed_object, repair_log). Defaults to False. - **kwargs** - Optional - Any keyword arguments accepted by `json.dumps()` for output formatting. ### Request Example ```python import json_repair # Replace json.loads() calls data = json_repair.loads('{"name": "Alice", "active": true}') # Returns: {'name': 'Alice', 'active': True} # Handle broken JSON transparently broken = '{"items": ["apple", "banana",]}' # trailing comma data = json_repair.loads(broken) # Returns: {'items': ['apple', 'banana']} # Missing quotes on keys malformed = "{name: John, age: 30}" data = json_repair.loads(malformed) # Returns: {'name': 'John', 'age': 30} # Get repair log data, log = json_repair.loads('{"key": value}', logging=True) # Returns: ({'key': 'value'}, [repair actions]) ``` ### Response #### Success Response (200) - **parsed_object** (dict or list) - The parsed Python object from the repaired JSON. - **repair_log** (list) - A list of repair actions performed, if `logging=True`. #### Response Example ```json { "name": "Alice", "active": true } ``` ``` -------------------------------- ### Untitled No description -------------------------------- ### Drop-in json.loads() Replacement in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt A convenience function that acts as a direct replacement for `json.loads()`, automatically repairing malformed JSON strings before parsing them into Python objects. It handles common issues like trailing commas and missing quotes transparently and can optionally return a repair log. ```python import json_repair # Replace json.loads() calls data = json_repair.loads('{"name": "Alice", "active": true}') # Returns: {'name': 'Alice', 'active': True} # Handle broken JSON transparently broken = '{"items": ["apple", "banana",]}' # trailing comma data = json_repair.loads(broken) # Returns: {'items': ['apple', 'banana']} # Missing quotes on keys malformed = "{name: John, age: 30}" data = json_repair.loads(malformed) # Returns: {'name': 'John', 'age': 30} # Get repair log data, log = json_repair.loads('{"key": value}', logging=True) # Returns: ({'key': 'value'}, [repair actions]) ``` -------------------------------- ### Untitled No description -------------------------------- ### Drop-in json.load() Replacement from File Descriptor in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt Replaces `json.load()` for reading and repairing JSON directly from a file descriptor. It supports chunked reading for large files with a configurable chunk size and can provide a repair log. It automatically handles common JSON errors within the file. ```python import json_repair # Read from file descriptor with open('data.json', 'r') as fd: data = json_repair.load(fd) # Handle broken JSON files with open('broken.json', 'r') as fd: data = json_repair.load(fd) # Automatically repairs: missing brackets, quotes, commas, etc. # Large file with custom chunk size (1MB chunks) with open('large.json', 'r') as fd: data = json_repair.load(fd, chunk_length=1048576) # Get repair log with open('data.json', 'r') as fd: data, log = json_repair.load(fd, logging=True) # Skip validation for performance with open('data.json', 'r') as fd: data = json_repair.load(fd, skip_json_loads=True) ``` -------------------------------- ### Replace json.load with json_repair.load in Python Source: https://github.com/mangiucugna/json_repair/blob/main/README.md This function acts as a replacement for Python's `json.load()`, designed to read and repair JSON data directly from a file descriptor. It handles potential errors during parsing, ensuring that even slightly malformed JSON files can be loaded successfully. It does not catch IO-related exceptions, which must be managed separately. ```python import json_repair try: file_descriptor = open('data.json', 'rb') except OSError as e: print(f"Error opening file: {e}") # Handle file opening error with file_descriptor: try: decoded_object = json_repair.load(file_descriptor) except Exception as e: print(f"Error loading JSON from file descriptor: {e}") # Handle JSON parsing error ``` -------------------------------- ### Load JSON from Filename Directly in Python Source: https://context7.com/mangiucugna/json_repair/llms.txt A utility function that simplifies loading JSON from a file by handling file opening and closing internally. It repairs any malformed JSON content within the file and returns the parsed Python object. Supports chunked reading for large files and can optionally provide repair logs. ```python from json_repair import from_file # Simple file loading data = from_file('config.json') # Handle IO exceptions yourself try: data = from_file('/path/to/data.json') except (OSError, IOError) as e: print(f"Failed to read file: {e}") # Large files with chunked reading data = from_file('large_dataset.json', chunk_length=2097152) # 2MB chunks # Get repair information data, log = from_file('data.json', logging=True) for entry in log: print(f"Repair: {entry['text']} at {entry['context']}") ``` -------------------------------- ### Replace json.loads with json_repair.loads in Python Source: https://github.com/mangiucugna/json_repair/blob/main/README.md This function serves as a drop-in replacement for Python's built-in `json.loads()`. It attempts to repair the JSON string before parsing it into a Python object, making it more resilient to errors. It accepts standard `json.loads` parameters and optional `skip_json_loads=True` to bypass internal JSON validation if already handled. ```python import json_repair json_string = "{'key': 'value'}" # Potentially malformed JSON string decoded_object = json_repair.loads(json_string) # Example bypassing internal JSON validation decoded_object_skipped = json_repair.loads(json_string, skip_json_loads=True) ``` -------------------------------- ### Untitled No description -------------------------------- ### Read JSON from File with json_repair.from_file in Python Source: https://github.com/mangiucugna/json_repair/blob/main/README.md This utility function reads and repairs JSON data directly from a specified file path. It simplifies the process of loading potentially corrupted JSON files into Python objects. The function handles file reading and JSON parsing, but users are responsible for managing any `OSError` or `IOError` exceptions that may occur during file operations. ```python import json_repair json_file_path = 'my_data.json' try: decoded_object = json_repair.from_file(json_file_path) except OSError as e: print(f"IOError: {e}") # Handle file system errors except IOError as e: print(f"JSONDecodeError: {e}") # Handle JSON parsing errors ``` -------------------------------- ### Untitled No description -------------------------------- ### Repair JSON String in Python Source: https://github.com/mangiucugna/json_repair/blob/main/README.md This function repairs a potentially malformed JSON string and returns a valid JSON string. It can handle various syntax errors, missing elements, and extra characters. If the string is extremely broken, it might return an empty string. It accepts optional parameters like `ensure_ascii` to preserve non-Latin characters and `return_objects` to directly return a Python object. ```python from json_repair import repair_json bad_json_string = "{'key': 'value'}" # Example of a bad JSON string good_json_string = repair_json(bad_json_string) # Example with non-Latin characters bad_json_chinese = "{'test_chinese_ascii':'统一码'}" repaired_chinese_ascii = repair_json(bad_json_chinese) repaired_chinese_unicode = repair_json(bad_json_chinese, ensure_ascii=False) # Example returning an object repaired_object = repair_json(bad_json_string, return_objects=True) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.