• Cleans and extracts valid JSON from various input formats including double-escaped strings, strings with embedded JSON, and markdown code blocks.

    This function handles multiple scenarios in the following priority order:

    1. Valid JSON: If the input is already valid JSON, it returns it formatted
    2. Double-escaped JSON: Handles strings with escaped quotes (\") and newlines (\n)
    3. Markdown blocks: Extracts JSON from ```json code blocks (only as last resort)
    4. Mixed content: Extracts JSON objects/arrays from strings with surrounding text

    @param inputString - The string to process, which may contain JSON in various formats @returns A formatted JSON string if valid JSON is found, otherwise null

    @example // Simple JSON CleanJSON('{"name": "test"}') // Returns: '{\n "name": "test"\n}'

    @example // Double-escaped JSON CleanJSON('{\"name\": \"test\", \"value\": 123}') // Returns: '{\n "name": "test",\n "value": 123\n}'

    @example // JSON with embedded markdown (preserves the markdown in string values) CleanJSON('{"text": "json\\n{\\"inner\\": true}\\n"}') // Returns: '{\n "text": "json\\n{\\"inner\\": true}\\n"\n}'

    @example // Markdown block extraction (only when not valid JSON) CleanJSON('Some text json\n{"extracted": true}\n more text') // Returns: '{\n "extracted": true\n}'

    Parameters

    • inputString: string

    Returns string | null