🔍 Code Extractor

function from_json

Maturity: 49

Parses a JSON string into a Python object, with error handling that logs parsing failures and returns None on error.

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
212 - 226
Complexity:
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

  • json
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function parse_date 54.2% similar

    Parses a date string in YYYY-MM-DD format into a datetime object, returning None if parsing fails or input is empty.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function to_json 52.9% similar

    Converts a Python object to a formatted JSON string with 2-space indentation, using a safe serialization helper function.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function parse_datetime 52.5% similar

    Parses a datetime string in YYYY-MM-DD HH:MM:SS format into a Python datetime object, returning None if parsing fails.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function safe_json_serialize 50.1% similar

    Recursively converts Python objects into JSON-serializable formats, with special handling for datetime objects and objects with to_dict() methods.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function safe_json_dumps 46.8% similar

    Safely serializes Python objects to JSON format, handling NaN values and datetime objects that would otherwise cause serialization errors.

    From: /tf/active/vicechatdev/full_smartstat/services.py
← Back to Browse