### Get Value at Specific Path in JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Retrieve the value at a specific path within a JSON structure using the `get_value_at_path` function. This is useful for accessing a known element directly. ```python from jsoninja.core import get_value_at_path data = {"a": {"b": [1, 2], "c": 3}} value = get_value_at_path(data, "a.b[1]") print(value) ``` -------------------------------- ### Get Value at Specific Path in JSON with JSONavigator Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Retrieves a value from a nested JSON structure using a dot-separated path with bracket notation for array indices. Supports custom separators. Parses the path string to navigate and return the target value. ```python from jsoninja import get_value_at_path data = { "company": { "employees": [ {"name": "Alice", "department": "Engineering"}, {"name": "Bob", "department": "Sales"}, {"name": "Charlie", "department": "Marketing"} ], "locations": { "headquarters": "New York", "branches": ["London", "Tokyo", "Sydney"] } } } # Get a simple nested value headquarters = get_value_at_path(data, "company.locations.headquarters") print(headquarters) # Output: New York # Get a value from an array first_employee = get_value_at_path(data, "company.employees[0]") print(first_employee) # Output: {'name': 'Alice', 'department': 'Engineering'} # Get a specific field from an array element second_employee_name = get_value_at_path(data, "company.employees[1].name") print(second_employee_name) # Output: Bob # Get a value from a nested array second_branch = get_value_at_path(data, "company.locations.branches[1]") print(second_branch) # Output: Tokyo # Using a custom separator value = get_value_at_path(data, "company/employees[2]/department", separator='/') print(value) # Output: Marketing ``` -------------------------------- ### Format JSON Path for Readability with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Make JSON paths more human-readable by using the `format_path` function. This function transforms standard JSON path notation into a more intuitive format. ```python from jsoninja.utils import format_path formatted_path = format_path("a.b[1]") print(formatted_path) ``` -------------------------------- ### Compare Two JSON Files or Objects with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Compare two JSON structures or files to identify differences using the `compare_files` function. It returns the changes and a summary. The `isPath` parameter distinguishes between file paths and loaded objects. ```python from jsoninja.compare import compare_files json1 = {"a": {"b": 1, "c": 2}} json2 = {"a": {"b": 1, "c": 3}} changes, summary = compare_files(json1, json2) print("Changes:", changes) print("Summary:", summary) ``` ```python from jsoninja.compare import compare_files file1_path = "path//to//first.json" # Using // as the path separator file2_path = r"path/to/second.json" # Using a raw formatted string changes, summary = compare_files(file1_path, file2_path, isPath=True) print("Changes:", changes) print("Summary:", summary) ``` -------------------------------- ### Find All Paths for a Key in JSON with JSONavigator Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Searches a JSON structure for all occurrences of a specific key and returns a list of their corresponding paths. Useful for identifying all instances of a field name in complex or repetitive JSON data. ```python from jsoninja import find_all_paths_for_element data = { "order": { "id": "ORD-001", "customer": { "id": "CUST-123", "name": "Jane Doe" }, "items": [ {"id": "ITEM-1", "name": "Laptop", "price": 999}, {"id": "ITEM-2", "name": "Mouse", "price": 29}, {"id": "ITEM-3", "name": "Keyboard", "price": 79} ], "shipping": { "address": { "id": "ADDR-456", "street": "123 Main St" } } } } # Find all paths where 'id' key exists id_paths = find_all_paths_for_element(data, "id") print(id_paths) ``` -------------------------------- ### Validate JSON Path Format with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Ensure that a JSON path string is correctly formatted using the `validate_path` function. It raises an `InvalidPathError` for malformed paths. ```python from jsoninja.utils import validate_path from jsoninja.exceptions import InvalidPathError try: validate_path("a.b[1]") except InvalidPathError as e: print(f"Invalid path: {e}") ``` -------------------------------- ### Find All Paths for Element in JSON Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Recursively searches a nested JSON structure to find all paths where a specified key exists. It returns a list of strings, where each string represents a unique path to an occurrence of the key. This function is useful for identifying all locations of a particular data field within complex JSON objects. ```python from jsoninja import find_all_paths_for_element data = { "order": { "id": "ORD-123", "customer": { "id": "CUST-456", "name": "Nikhil Singh" }, "items": [ {"id": "ITEM-001", "name": "Laptop", "price": 1200.00}, {"id": "ITEM-002", "name": "Mouse", "price": 25.50}, {"id": "ITEM-003", "name": "Keyboard", "price": 75.00} ], "shipping": { "address": { "id": "ADDR-789", "street": "123 Main St", "city": "Anytown" } } } } # Find all paths where 'id' key exists id_paths = find_all_paths_for_element(data, "id") print(id_paths) # Output: ['order.id', 'order.customer.id', 'order.items[0].id', # 'order.items[1].id', 'order.items[2].id', 'order.shipping.address.id'] # Find all paths where 'name' key exists name_paths = find_all_paths_for_element(data, "name") print(name_paths) # Output: ['order.customer.name', 'order.items[0].name', # 'order.items[1].name', 'order.items[2].name'] # Find all paths where 'price' key exists price_paths = find_all_paths_for_element(data, "price") print(price_paths) # Output: ['order.items[0].price', 'order.items[1].price', 'order.items[2].price'] ``` -------------------------------- ### Empty All Values in JSON Structure with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Replace all values in a nested JSON structure with empty strings using `empty_all_the_values`. For non-object/array inputs, it returns None. ```python from jsoninja.core import empty_all_the_values data = { "a": 1, "b": {"c": 42, "d": [1, 2, {"e": "hello"}]}, "f": [True, {"g": "world"}], } emptied_data = empty_all_the_values(data) print(emptied_data) ``` -------------------------------- ### Traverse JSON Data with JSONavigator Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Recursively traverses a nested JSON structure and yields (path, value) tuples for each leaf node. Supports custom separators for path formatting. Useful for memory-efficient iteration over complex JSON. ```python from jsoninja import traverse_json # Sample nested JSON data data = { "user": { "name": "John", "emails": ["john@example.com", "john.doe@work.com"], "profile": { "age": 30, "active": True } }, "settings": { "theme": "dark", "notifications": [ {"type": "email", "enabled": True}, {"type": "sms", "enabled": False} ] } } # Traverse and print all paths and values for path, value in traverse_json(data): print(f"Path: {path}, Value: {value}") # Output: # Path: user.name, Value: John # Path: user.emails[0], Value: john@example.com # Path: user.emails[1], Value: john.doe@work.com # Path: user.profile.age, Value: 30 # Path: user.profile.active, Value: True # Path: settings.theme, Value: dark # Path: settings.notifications[0].type, Value: email # Path: settings.notifications[0].enabled, Value: True # Path: settings.notifications[1].type, Value: sms # Path: settings.notifications[1].enabled, Value: False # Using a custom separator for path, value in traverse_json(data, separator='/'): print(f"Path: {path}, Value: {value}") # Output: # Path: user/name, Value: John # Path: user/emails[0], Value: john@example.com # ... ``` -------------------------------- ### Customize JSON Traversal Separator in JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Customize the path separator used in JSON traversal functions like `traverse_json` by providing a `separator` argument. This allows for flexible path representation. ```python from jsoninja.core import traverse_json data = {"a": {"b": [1, 2], "c": 3}} for path, value in traverse_json(data, seperator='*'): print(f"Path: {path}, Value: {value}") ``` -------------------------------- ### Format JSON Path String - Python Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Formats a JSON path string by replacing the default or custom separator with an arrow notation (' -> ') for enhanced readability. This is useful for displaying paths in user interfaces or logs. Supports custom separators. ```python from jsoninja import format_path # Format a simple path formatted = format_path("user.profile.name") print(formatted) # Output: user -> profile -> name # Format a path with array indices formatted = format_path("orders[0].items[2].price") print(formatted) # Output: orders[0] -> items[2] -> price # Format a complex path formatted = format_path("company.departments[0].employees[1].contact.email") print(formatted) # Output: company -> departments[0] -> employees[1] -> contact -> email # Using a custom separator formatted = format_path("user/profile/settings", separator='/') print(formatted) # Output: user -> profile -> settings ``` -------------------------------- ### Compare JSON Structures - Python Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Compares two JSON structures (objects or files) to identify differences such as added, removed, changed, and type-changed values. It returns a list of detailed changes and a summary of the comparison. Can accept parsed JSON objects or file paths. ```python from jsoninja import compare_files # Compare two JSON objects directly json1 = { "name": "Product A", "price": 100, "stock": 50, "categories": ["electronics", "gadgets"], "details": { "weight": "500g", "color": "black" } } json2 = { "name": "Product A", "price": 120, # Changed "stock": 50, "categories": ["electronics", "gadgets", "new"], # Added item "details": { "weight": "500g", "color": "white", # Changed "material": "plastic" # Added }, "discount": 10 # Added } changes, summary = compare_files(json1, json2) print("Changes found:") for change in changes: print(change) # Output: # {'type': 'changed', 'path': 'price', 'old_value': 100, 'new_value': 120} # {'type': 'added', 'path': 'categories[2]', 'new_value': 'new'} # {'type': 'changed', 'path': 'details-->color', 'old_value': 'black', 'new_value': 'white'} # {'type': 'added', 'path': 'details-->material', 'new_value': 'plastic'} # {'type': 'added', 'path': 'discount', 'new_value': 10} print("\nSummary:") print(summary) # Output: {'added': 3, 'removed': 0, 'changed': 2, 'type_changed': 0, 'unknown': 0} # Compare two JSON files by path changes, summary = compare_files( "path//to//file1.json", "path//to//file2.json", isPath=True ) # Or using raw strings for file paths changes, summary = compare_files( r"path/to/file1.json", r"path/to/file2.json", isPath=True ) # Handling identical JSON structures identical_json = {"key": "value"} changes, summary = compare_files(identical_json, identical_json) print(summary) # Output: {'message': 'No differences found. The JSON files are identical.'} ``` -------------------------------- ### Find Value of Element by Key in JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Search for a specific key within a nested JSON structure and retrieve its associated value using `find_value_of_element`. Returns an empty string if the key is not found. ```python from jsoninja.core import find_value_of_element data = {"a": {"b": {"c": 42}}} value = find_value_of_element("c", data) print(value) ``` -------------------------------- ### Find Value of Element in JSON Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Recursively searches for the first occurrence of a target key in a nested JSON structure and returns its associated value. If the key is not found, it returns an empty string. This function is useful for quickly extracting a specific value without needing to know its exact path. ```python from jsoninja import find_value_of_element data = { "response": { "status": "success", "data": { "user": { "profile": { "email": "user@example.com", "preferences": { "language": "en", "timezone": "UTC" } } }, "metadata": { "timestamp": "2024-01-15T10:30:00Z", "version": "2.0" } } } } # Find the first occurrence of 'email' email = find_value_of_element("email", data) print(email) # Output: user@example.com # Find the first occurrence of 'timezone' timezone = find_value_of_element("timezone", data) print(timezone) # Output: UTC # Find the first occurrence of 'version' version = find_value_of_element("version", data) print(version) # Output: 2.0 # Search for a non-existent key returns empty string missing = find_value_of_element("nonexistent_key", data) print(f"Result: '{missing}'") # Output: Result: '' ``` -------------------------------- ### Traverse Nested JSON with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Recursively traverse a nested JSON structure to extract paths and values using the `traverse_json` function. This function is useful for iterating through all elements of a JSON object. ```python from jsoninja.core import traverse_json data = {"a": {"b": [1, 2], "c": 3}} for path, value in traverse_json(data): print(f"Path: {path}, Value: {value}") ``` -------------------------------- ### Flatten JSON Structure Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Converts a nested JSON structure into a single-level dictionary. The keys of the new dictionary represent the full paths to the values in the original JSON, using a specified separator (default is '.'). This is useful for data processing and exporting to flat formats. ```python from jsoninja import flatten_json data = { "product": { "id": "PRD-001", "details": { "name": "Wireless Headphones", "brand": "AudioTech", "specs": { "battery": "40 hours", "bluetooth": "5.0" } }, "prices": [99.99, 89.99, 79.99], "tags": ["electronics", "audio", "wireless"] } } # Flatten the JSON structure flat = flatten_json(data) print(flat) # Output: # { # 'product.id': 'PRD-001', # 'product.details.name': 'Wireless Headphones', # 'product.details.brand': 'AudioTech', # 'product.details.specs.battery': '40 hours', # 'product.details.specs.bluetooth': '5.0', # 'product.prices[0]': 99.99, # 'product.prices[1]': 89.99, # 'product.prices[2]': 79.99, # 'product.tags[0]': 'electronics', # 'product.tags[1]': 'audio', # 'product.tags[2]': 'wireless' # } # Using a custom separator flat_custom = flatten_json(data, separator='/') print(flat_custom) # Output: # { # 'product/id': 'PRD-001', # 'product/details/name': 'Wireless Headphones', # ... # } ``` -------------------------------- ### Validate JSON Path String - Python Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Validates if a given JSON path string is correctly formatted, checking for valid characters and balanced brackets. It raises an InvalidPathError for malformed paths and returns True for valid ones. Supports custom separators. ```python from jsoninja import validate_path from jsoninja.exceptions import InvalidPathError # Valid paths result = validate_path("user.name") print(result) # Output: True result = validate_path("items[0].price") print(result) # Output: True result = validate_path("data.users[2].profile.settings[0]") print(result) # Output: True # Invalid paths - handling errors try: validate_path("user.name@email") # Invalid character '@' except InvalidPathError as e: print(f"Error: {e}") # Output: Error: Invalid character '@' in path. try: validate_path("items[0.price") # Mismatched brackets except InvalidPathError as e: print(f"Error: {e}") # Output: Error: Mismatched brackets in path. try: validate_path(12345) # Non-string input except InvalidPathError as e: print(f"Error: {e}") # Output: Error: Path must be a string. # Using a custom separator result = validate_path("user/profile/name", separator='/') print(result) # Output: True ``` -------------------------------- ### Handle Element Not Found Errors - Python Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Custom exception `ElementNotFoundError` is raised when a specific element is not found during a search within a JSON structure. The exception includes the name of the element that was searched for, facilitating error identification. ```python from jsoninja.exceptions import ElementNotFoundError # Example of raising and catching ElementNotFoundError try: raise ElementNotFoundError("username") except ElementNotFoundError as e: print(f"Search failed: {e}") # Output: Search failed: Element not found in JSON structure. Element: username ``` -------------------------------- ### Flatten Nested JSON with JSONavigator Source: https://github.com/nikhil-singh-2503/jsonavigator/blob/main/README.md Convert a nested JSON structure into a single-level dictionary using the `flatten_json` function. This simplifies data access by removing nesting. ```python from jsoninja.utils import flatten_json data = {"a": {"b": [1, 2], "c": 3}} flattened = flatten_json(data) print(flattened) ``` -------------------------------- ### Empty All Values in JSON Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Recursively replaces all values within a nested JSON structure (dictionaries and lists) with empty strings. This function modifies the original data in place and returns the modified structure. It is useful for creating JSON templates or sanitizing data. ```python from jsoninja import empty_all_the_values import copy data = { "user": { "name": "John Doe", "age": 30, "active": True, "scores": [95, 87, 92], "address": { "street": "123 Main St", "city": "Boston", "zip": "02101" } }, "settings": { "theme": "dark", "notifications": True } } # Make a copy to preserve original data data_copy = copy.deepcopy(data) # Empty all values result = empty_all_the_values(data_copy) print(result) # Output: # { # "user": { # "name": "", # "age": "", # "active": "", # "scores": ["", "", ""], # "address": { # "street": "", # "city": "", # "zip": "" # } # }, # "settings": { # "theme": "", # "notifications": "" # } # } # Invalid inputs return None result = empty_all_the_values("not a dict or list") print(result) # Output: None result = empty_all_the_values(12345) print(result) # Output: None ``` -------------------------------- ### Handle Invalid Path Errors - Python Source: https://context7.com/nikhil-singh-2503/jsonavigator/llms.txt Custom exception `InvalidPathError` is raised when a JSON path string is malformed, containing invalid characters or unbalanced brackets. This exception aids in debugging and validating path inputs. ```python from jsoninja.exceptions import InvalidPathError # Example of catching InvalidPathError try: from jsoninja import validate_path validate_path("invalid..path") except InvalidPathError as e: print(f"Path validation failed: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.