(body: string)
| 1892 | * @throws {Error} - Detailed error message with suggestions for common JSON issues |
| 1893 | */ |
| 1894 | export const parseJsonBody = (body: string): any => { |
| 1895 | try { |
| 1896 | // First try to parse as-is with JSON5 (which handles more cases than standard JSON) |
| 1897 | return JSON5.parse(body) |
| 1898 | } catch (error) { |
| 1899 | try { |
| 1900 | // If that fails, try to clean up common issues |
| 1901 | let cleanedBody = body |
| 1902 | |
| 1903 | // 1. Remove unnecessary backslash escapes for square brackets and braces |
| 1904 | // eslint-disable-next-line |
| 1905 | cleanedBody = cleanedBody.replace(/\\(?=[\[\]{}])/g, '') |
| 1906 | |
| 1907 | // 2. Fix single quotes to double quotes (but preserve quotes inside strings) |
| 1908 | cleanedBody = cleanedBody.replace(/'/g, '"') |
| 1909 | |
| 1910 | // 3. Remove trailing commas before closing brackets/braces |
| 1911 | cleanedBody = cleanedBody.replace(/,(\s*[}\]])/g, '$1') |
| 1912 | |
| 1913 | // 4. Remove comments (// and /* */) |
| 1914 | cleanedBody = cleanedBody |
| 1915 | .replace(/\/\/.*$/gm, '') // Remove single-line comments |
| 1916 | .replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments |
| 1917 | |
| 1918 | return JSON5.parse(cleanedBody) |
| 1919 | } catch (secondError) { |
| 1920 | try { |
| 1921 | // 3rd attempt: try with standard JSON.parse on original body |
| 1922 | return JSON.parse(body) |
| 1923 | } catch (thirdError) { |
| 1924 | try { |
| 1925 | // 4th attempt: try with standard JSON.parse on cleaned body |
| 1926 | const finalCleanedBody = body |
| 1927 | // eslint-disable-next-line |
| 1928 | .replace(/\\(?=[\[\]{}])/g, '') // Basic escape cleanup |
| 1929 | .replace(/,(\s*[}\]])/g, '$1') // Remove trailing commas |
| 1930 | .trim() |
| 1931 | |
| 1932 | return JSON.parse(finalCleanedBody) |
| 1933 | } catch (fourthError) { |
| 1934 | // Provide comprehensive error message with suggestions |
| 1935 | const suggestions = [ |
| 1936 | '• Ensure all strings are enclosed in double quotes', |
| 1937 | '• Remove trailing commas', |
| 1938 | '• Remove comments (// or /* */)', |
| 1939 | '• Escape special characters properly (\\n for newlines, \\" for quotes)', |
| 1940 | '• Use double quotes instead of single quotes', |
| 1941 | '• Remove unnecessary backslashes before brackets [ ] { }' |
| 1942 | ] |
| 1943 | |
| 1944 | throw new Error( |
| 1945 | `Invalid JSON format in body. Original error: ${error.message}. ` + |
| 1946 | `After cleanup attempts: ${secondError.message}. 3rd attempt: ${thirdError.message}. Final attempt: ${fourthError.message}.\n\n` + |
| 1947 | `Common fixes:\n${suggestions.join('\n')}\n\n` + |
| 1948 | `Received body: ${body.substring(0, 200)}${body.length > 200 ? '...' : ''}` |
| 1949 | ) |
| 1950 | } |
| 1951 | } |
no test coverage detected