| 439 | return value; |
| 440 | } |
| 441 | function createHelpfulJsonError(e: any, trimmedValue: string) { |
| 442 | const errorMessage = e.message || 'Invalid JSON' |
| 443 | |
| 444 | // Extract position info if available |
| 445 | const positionMatch = errorMessage.match(/position\s+(\d+)/i) |
| 446 | const position = positionMatch ? parseInt(positionMatch[1], 10) : null |
| 447 | |
| 448 | let helpfulMessage = 'Invalid JSON: ' |
| 449 | |
| 450 | // Check for common mistakes |
| 451 | if (trimmedValue.includes("'") && !trimmedValue.includes('"')) { |
| 452 | helpfulMessage += "Use double quotes (\") instead of single quotes (') for strings." |
| 453 | } else if (/,\s*[}\]]/.test(trimmedValue)) { |
| 454 | helpfulMessage += "Trailing comma found. Remove the comma before the closing bracket." |
| 455 | } else if (errorMessage.includes('Unexpected token')) { |
| 456 | if (position !== null) { |
| 457 | const contextStart = Math.max(0, position - 10) |
| 458 | const contextEnd = Math.min(trimmedValue.length, position + 10) |
| 459 | const context = trimmedValue.substring(contextStart, contextEnd) |
| 460 | helpfulMessage += `Unexpected character near position ${position}: "...${context}..."` |
| 461 | } else { |
| 462 | helpfulMessage += errorMessage |
| 463 | } |
| 464 | } else if (errorMessage.includes('Unexpected end')) { |
| 465 | helpfulMessage += "JSON is incomplete. Check for missing closing brackets or quotes." |
| 466 | } else { |
| 467 | helpfulMessage += errorMessage |
| 468 | } |
| 469 | return helpfulMessage |
| 470 | } |
| 471 | function parseJSON(value: any): { parsed: any; error: string | null } { |
| 472 | if (typeof value !== 'string') { |
| 473 | return { parsed: value, error: null }; |