function from_json
Parses a JSON string into a Python object, with error handling that logs parsing failures and returns None on error.
/tf/active/vicechatdev/CDocs/utils/__init__.py
212 - 226
simple
Purpose
This function provides a safe wrapper around json.loads() for converting JSON strings into Python objects. It handles JSONDecodeError exceptions gracefully by logging the error and returning None instead of raising an exception, making it suitable for scenarios where JSON parsing failures should not crash the application.
Source Code
def from_json(json_str: str) -> Any:
"""
Parse JSON string into Python object.
Args:
json_str: JSON string
Returns:
Parsed object
"""
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
json_str |
str | - | positional_or_keyword |
Parameter Details
json_str: A string containing valid JSON data to be parsed. Expected to be a properly formatted JSON string representing objects, arrays, strings, numbers, booleans, or null values. Invalid JSON will trigger error handling.
Return Value
Type: Any
Returns a Python object (dict, list, str, int, float, bool, or None) corresponding to the parsed JSON structure. If parsing fails due to invalid JSON syntax, returns None instead of raising an exception. The return type is Any, meaning it can be any valid Python type that JSON can represent.
Dependencies
jsonlogging
Required Imports
import json
import logging
Usage Example
import json
import logging
# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
def from_json(json_str: str):
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON: {e}")
return None
# Valid JSON
valid_json = '{"name": "John", "age": 30}'
result = from_json(valid_json)
print(result) # Output: {'name': 'John', 'age': 30}
# Invalid JSON
invalid_json = '{name: John}'
result = from_json(invalid_json)
print(result) # Output: None (error logged)
Best Practices
- Always check if the return value is None before using it, as this indicates a parsing failure
- Ensure a logger is properly configured before calling this function to capture error messages
- Consider the security implications when parsing JSON from untrusted sources
- For production use, consider adding more specific error handling or validation based on expected JSON structure
- If you need to distinguish between valid JSON null and parsing errors, consider modifying the function to return a tuple (success, result) or raise exceptions instead
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function parse_date 54.2% similar
-
function to_json 52.9% similar
-
function parse_datetime 52.5% similar
-
function safe_json_serialize 50.1% similar
-
function safe_json_dumps 46.8% similar