Prompt JSON Formatter

Runs 100% in your browser

Detect, validate, and format JSON blocks embedded inside any prompt — surrounding prose and template variables preserved exactly.

Frequently asked questions

Prompt JSON Formatter is a browser-only tool that finds JSON objects or arrays embedded inside a prompt, formats them with your chosen indentation, and returns the complete prompt with the surrounding prose, Markdown, URLs, and template variables preserved exactly as written. It is distinct from the general JSON Formatter, which operates on pure JSON documents, and from Prompt Formatter, which handles general prompt presentation without JSON-specific detection or validation.

The JSON Formatter tool expects the entire input to be a JSON document. Prompt JSON Formatter accepts a full prompt — prose, instructions, examples, and template variables mixed with JSON — then detects which parts are JSON, lets you choose which block to format, and preserves everything else unchanged. If you paste a raw JSON document into Prompt JSON Formatter, it works too, but the general JSON Formatter is simpler for that case.

Detection happens in two passes. First, fenced code blocks using triple backticks (```json ... ``` or ``` ... ```) are scanned; a block is considered a JSON candidate if it is declared as json or if its trimmed content starts with { or [. Second, the plain text is scanned with a bracket-balancing parser to find unambiguous bare JSON objects and arrays that are not inside quoted spans, URLs, or already-captured fence ranges. Only bare candidates that pass JSON.parse are shown to avoid noise from brace-heavy prose.

When multiple candidates are detected, the tool lists them all and requires you to select one before formatting. The Format button stays disabled until a candidate is explicitly selected. This prevents accidentally formatting the wrong block and makes the choice traceable.

After formatting, every character outside the selected JSON block — instructions, role descriptions, examples, headings, Markdown syntax, URLs, and template variables such as {{payload}} or ${json} — is returned exactly as you wrote it. The tool only replaces the raw JSON span with its formatted equivalent. Nothing else is touched.

No. If a candidate fails JSON.parse, it is shown as "Invalid JSON" in the candidate list with the error message and, where available, the line and column. The Format button is disabled for invalid candidates. To repair the JSON first, follow the link to the JSON Repair tool, fix the issues there, then paste the corrected text back into Prompt JSON Formatter.

No. These are not valid JSON and will cause the candidate to be shown as "Invalid JSON." The tool uses the standard browser JSON.parse engine, which does not accept comments, trailing commas, single-quoted string values, or unquoted object keys. If your JSON uses these patterns, use the JSON Repair tool first.

Four options are available: 2 spaces (the default and most common), 4 spaces (common in Python-adjacent environments), Tabs (for codebases that require hard tabs), and Compact (removes all whitespace, producing the smallest possible JSON for embedding in system prompts where token count matters).

When formatting a bare JSON block — one not already inside triple backticks — you can check "Wrap bare JSON in ```json fence" to automatically surround the formatted JSON with ```json and ``` markers. This makes the block unambiguous in Markdown-rendered environments such as GitHub, Notion, and many LLM system prompt editors.

Yes. Template variables are outside the selected JSON block and are never touched. If a variable appears inside the selected JSON value (for example "data": "{{input}}"), it is preserved verbatim because JSON.stringify round-trips the string content unchanged as long as the variable is quoted as a JSON string.

Brace pairs inside JSON string values are not matched by the scanner because the scanner skips quoted content. During formatting, JSON.stringify preserves all string contents exactly, including any { or } characters inside string values. Nested objects and arrays are formatted by JSON.stringify's own algorithm, which is always correct.

JSON.parse converts numbers to JavaScript IEEE 754 doubles. Very large integers (beyond 2^53 − 1) may lose precision — this is a documented JavaScript behaviour, not a bug introduced by this tool. Unicode escape sequences (\uXXXX) in the original JSON are decoded by JSON.parse and re-encoded by JSON.stringify only if the character falls outside BMP — for most text this means the string content is preserved. If your JSON contains high-precision integer IDs, verify them independently.

Yes. YAML or XML blocks are treated as prose. The fenced-block scanner only picks up ``` or ~~~ fences; it recognises ```json fences specifically. A ```yaml or ```xml block is not returned as a JSON candidate. Plain text that looks like YAML or XML is also ignored because only text starting with { or [ is considered for bare-candidate matching.

Yes. The entire detection, formatting, and validation pipeline runs synchronously in your browser tab using vanilla JavaScript and the native JSON.parse / JSON.stringify engine. No network requests are made at any point. You can use the tool offline or in an air-gapped environment.

No. Your prompt text exists only in the page's in-memory JavaScript state and in the browser's textarea DOM elements. It is never written to localStorage, sessionStorage, IndexedDB, cookies, or any URL parameter. Session history (the last 8 formatted results) is stored only in JavaScript memory and is cleared when you close or refresh the tab.

The session history stores the last 8 formatting operations in memory. Each entry records the original input text, the formatted full prompt, the formatted JSON block, the indentation setting used, and which candidate was selected. Clicking Restore on a history entry reloads the input and outputs so you can review or adjust a previous result without re-pasting.

The Swap button moves the full formatted prompt from the output pane into the input textarea, clears the outputs, and resets the candidate list. This lets you run a second formatting pass on an already-formatted prompt — for example if you change the indent setting and want to reformat, or if you added new JSON blocks by editing the output.

Yes. Click the Open file button to select a local .txt, .md, .prompt, .json, or .log file. The file is read with the browser FileReader API entirely in memory. No data is sent anywhere. The file content appears in the input editor and you can then click Detect to scan it.

The bare-object scanner skips short quoted spans (under 300 characters) to avoid false positives from string literals in prose, but very long prose sentences containing JSON-like text may still produce spurious candidates. Fenced blocks without a json label whose content does not start with { or [ are ignored. Deeply nested JSON inside a Markdown blockquote or HTML comment is not specially handled — the scanner sees it as plain text and attempts bracket matching. When in doubt, use an explicit ```json fence around your JSON block.

This tool makes no claims about model behaviour. Formatting JSON makes it easier for human reviewers to read and verify, and a well-formed code fence prevents some models from confusing JSON with prose. Whether indentation or fence syntax affects a specific model's output is a model-specific empirical question and not something this tool can determine.

JSON Repair fixes structural errors in invalid JSON — trailing commas, single-quoted strings, missing brackets, comments, and similar issues. Prompt JSON Formatter does not fix anything: it only formats already-valid JSON while leaving the surrounding prompt intact. If your JSON candidate is shown as Invalid JSON, use JSON Repair first, then come back here to format the corrected result.

Prompt Markdown Formatter handles the Markdown structure of a prompt — heading spacing, list marker normalisation, blockquote formatting, and paragraph spacing — while protecting code fences and inline code from modification. It does not parse or reformat the JSON inside those fences. Prompt JSON Formatter is the complement: it reaches inside the code fences, validates the JSON, and reformats it, while leaving the Markdown around the fence unchanged.

Lenient mode (labelled "Lenient mode (JSONC)" in the options bar) pre-processes the JSON candidate before passing it to JSON.parse. It strips // line comments, /* */ block comments, and trailing commas after the last property or array item — the three most common patterns in JSONC (JSON with Comments) files and in JSON written by AI models or copied from config files. Use it when your JSON candidate is shown as "Invalid JSON" due to comments or trailing commas, and you do not want to run the full JSON Repair tool. Lenient mode does not modify any other aspect of the JSON and does not change the surrounding prompt. Note: lenient mode outputs standard JSON — the comments and trailing commas are not present in the formatted output.

The Quick Fix button appears on each invalid JSON candidate card. Clicking it runs a targeted repair on that candidate: it strips // line comments, /* */ block comments, and trailing commas, then normalises single-quoted strings to double-quoted strings. The repaired text is validated against JSON.parse. If the repair succeeds, the candidate status changes to "Valid JSON" and the Format button becomes enabled — no full JSON Repair round-trip required. If the repair cannot produce valid JSON (for example, the JSON has structural issues like mismatched brackets), the tool reports the remaining error so you know what still needs fixing.

Paste the full ChatGPT prompt — including your role description, instructions, and any JSON examples or schemas — into the Prompt input area. The tool automatically detects the JSON blocks. If there is only one JSON block, it is auto-selected. Click Format selected (or press Ctrl+Enter) to reformat it with your chosen indentation. The output pane shows the complete prompt with the JSON block formatted and all surrounding instructions, role text, and template variables left exactly as written. You can then copy the full formatted prompt and paste it directly into ChatGPT or the OpenAI API.

The process is identical to formatting JSON in a ChatGPT prompt. Paste your Claude prompt into the input area — system instructions, Human/Assistant turns, XML tags, and JSON blocks all pass through without any parsing of the non-JSON parts. The tool detects only the JSON candidates and leaves everything else untouched, including Anthropic-specific syntax like <documents>, <examples>, or prompt chaining separators. Format the selected candidate, then copy the full formatted prompt for use in the Claude API or the Anthropic Console.

Paste your Gemini prompt into the input area. Gemini prompts sometimes use inline JSON schemas for structured output mode, bare JSON objects as context, or fenced JSON examples in multi-turn conversations. The tool detects all three patterns. If the JSON uses lenient syntax (such as comments or trailing commas, which can appear when JSON is generated by a model for illustration), enable Lenient mode before clicking Detect to include those candidates. Format the selected block, then copy the result back into Vertex AI Studio or the Gemini API request body.

"Format all valid" applies your current indentation, key-sorting, and fence-wrapping settings to every valid JSON candidate in the prompt in a single operation. It processes the candidates in reverse source order so that replacing one block does not affect the character positions of the others. The full formatted prompt — with all candidates reformatted — appears in the output pane. This is especially useful for few-shot prompts that contain two or more JSON examples: you can format all examples at once instead of selecting and formatting each one individually.

The Highlighted tab in the JSON output panel renders the formatted JSON with colour-coded syntax: object keys are shown in blue, string values in green, numbers in orange, booleans (true/false) in purple, null in red, and punctuation (brackets, commas, colons) in muted grey. This makes deeply nested JSON immediately scannable — you can find the field you need by scanning the colour pattern rather than parsing the text. The plain text tab shows the raw formatted JSON as a copyable textarea if you prefer that view.

The Tree view tab renders the formatted JSON as a collapsible interactive tree. Each object shows its keys and values; each array shows its indexed items. Click the ▾ triangle next to any object or array to collapse it, hiding its children and showing a summary count (e.g., "3 keys" or "5 items"). This lets you navigate large JSON structures without scrolling through hundreds of lines of text. The tree view is read-only — it does not allow editing. To edit the JSON, switch to the Plain text tab, modify the textarea content, then paste it back into the input if needed.

"Copy escaped" copies the formatted JSON as a valid JSON string literal — with all internal double quotes backslash-escaped (\"), newlines replaced with \n, tabs with \t, and backslashes doubled (\\). This is the exact format needed when you want to embed the JSON as a value inside another JSON document, for example as the value of a "prompt" or "system" field in an API request body. Without this transformation, pasting multi-line JSON inside a JSON string would produce malformed outer JSON.

Each detected candidate shows a "~N tokens" chip in its header. This is the estimated token count of the JSON in compact form (all whitespace removed), calculated as Math.ceil(compactLength / 4). This is the same approximation used by most token-counting tools for models that use byte-pair encoding. It gives you a quick sense of the token budget impact of including that JSON block in your prompt — particularly useful for choosing between 2-space, 4-space, and compact formatting modes before you click Format.

What is Prompt JSON Formatter?

What Is JSON Inside a Prompt?

When developers and AI engineers write prompts for language models, they routinely embed structured data as JSON. A prompt might contain a reference schema for the model to follow, a sample record for a data extraction task, a configuration object for a structured-output task, or an example payload for a few-shot demonstration. In every case, the JSON lives alongside prose instructions — and the two must coexist without the formatter confusing one for the other.

Prompt JSON Formatter is a browser tool designed specifically for this situation. It accepts the full prompt text — instructions, role descriptions, template variables, Markdown headings, and all — detects which parts are JSON, validates them without altering anything, lets you choose which block to format, and returns the complete prompt with the surrounding prose preserved character-for-character. It is distinct from the general JSON Formatter, which expects the entire input to be a JSON document; it is also distinct from Prompt Formatter and Prompt Markdown Formatter, which handle presentation of the non-JSON parts.

Candidate Detection: Fenced Blocks and Bare JSON

Detection runs in two passes. The first pass finds fenced code blocks — triple-backtick or triple-tilde delimiters — whose content starts with { or [, or whose opening delimiter is explicitly labelled ```json``. Fenced blocks are the preferred way to embed JSON in a prompt because the delimiters make boundaries unambiguous: the formatter knows exactly where the JSON starts and ends, and can replace just the inner content without touching the fence markers.

The second pass finds bare JSON{ or [ characters in the prompt text that are not inside a quoted span, a URL, or an already-captured fenced range. A bracket-balancing scanner walks the text, tracking nesting depth and skipping string interiors, until it finds a balanced top-level object or array. That span is then sent to JSON.parse. Only spans that parse successfully are shown as bare candidates; this keeps the list free of noise from brace-heavy prose or code fragments.

When a single candidate is found and it is valid, it is auto-selected. When multiple candidates are found, the Format button stays disabled until you explicitly choose one — this prevents accidental formatting of the wrong block.

Validation Without Silent Repair

Every candidate is validated using the browser's standard JSON.parse engine. If parsing succeeds, the candidate shows a green "Valid JSON" badge and the Format button is enabled. If parsing fails, the candidate shows a red "Invalid JSON" badge, displays the error message from the engine, and — where the browser provides it — the line and column where the error occurred. The Format button is disabled for invalid candidates.

The tool does not silently repair invalid JSON. It does not remove trailing commas, strip comments, convert single-quoted strings to double-quoted strings, or quote unquoted object keys. These are structural corrections, not formatting decisions, and making them silently would change the semantics of the JSON without the author's knowledge. If your JSON contains these patterns, the tool links directly to JSON Repair so you can fix the structural issues first, then come back to format the result.

Surrounding Prompt Preserved Exactly

Once you select a candidate and click Format, the tool computes the formatted JSON using JSON.stringify with your chosen indentation, then reconstructs the full prompt by replacing only the raw JSON span with the formatted output. Every character before the span and every character after it — prose, instructions, Markdown syntax, URLs, template variables such as {{payload}} or ${json}, and variables like [SCHEMA] or <example> — is returned exactly as written.

For fenced candidates, the fence markers (```json and ```) are also preserved. For bare candidates, an optional "Wrap in code fence" checkbox automatically surrounds the formatted JSON with ``json … ```` markers, making the boundary explicit for downstream tools and human reviewers.

The output pane shows the full formatted prompt for copy or download. A separate panel shows just the formatted JSON block for cases where you only need the JSON portion.

Common use cases

  • Formatting a compact inline JSON schema in a system prompt before sending it to an API — making it readable for review without changing the surrounding instructions
  • Detecting and validating the JSON payload in a data-extraction prompt before deploying it to a batch pipeline
  • Wrapping a bare JSON example in a ```json fence so that Markdown-aware environments (GitHub, Notion, LLM playgrounds) render it as a code block
  • Compacting a multi-line JSON example to a single line in a token-constrained system prompt
  • Switching a JSON block between 2-space, 4-space, and tab indentation to match team conventions without touching the surrounding instructions
  • Validating that a JSON template variable substitution produced well-formed JSON before using it in a model call
  • Reviewing a third-party prompt template that embeds JSON — checking that the JSON is structurally valid without uploading the prompt to an external service
  • Preparing a prompt for Prompt Compare by ensuring both versions have consistently formatted JSON, so the diff only shows meaningful changes

Why use ToolsSonic's Prompt JSON Formatter?

No general-purpose JSON formatter is designed to operate on prompts. Paste a prompt with prose and JSON into a standard JSON formatter and it will error immediately because the surrounding text is not valid JSON. Paste it into a text editor and you have to manually locate the JSON, extract it, format it elsewhere, and paste it back — error-prone and slow.

Prompt JSON Formatter is the only browser tool built specifically for JSON embedded inside prompt text. It handles the full prompt as input, surfaces only the JSON candidates, and requires explicit selection before formatting — so you always know exactly which block was touched and which prose was left unchanged.

Privacy is precise. The detection, validation, and formatting pipeline runs entirely in synchronous vanilla JavaScript using the browser's native JSON.parse and JSON.stringify. There is no fetch call, no WebSocket, no API request, and no storage write at any point. Your prompt exists only in the browser tab's memory and is cleared when you close or refresh the page.

Validation is honest. The tool reports "Invalid JSON" and shows the parser's error message rather than silently accepting broken input. The Format button is disabled for invalid candidates, not greyed-out with a misleading tooltip. To fix structural issues, there is a direct link to JSON Repair.

Scope is narrow by design. The tool formats JSON. It does not optimize prompts, analyse intent, suggest improvements, generate content, or make claims about how JSON formatting affects model behaviour. Those are separate concerns covered by separate tools.

Detection Rules and Behaviour Reference

Input patternDetected asValidity checkNotes
```json {…} ```Fenced block (preferred)JSON.parse on block bodyFence markers preserved; block body formatted in place
``` {…} ```Fenced block (unlabelled)JSON.parse on block bodyAccepted if body starts with { or [; fence markers preserved
~~~json {…} ~~~Fenced block (tilde fence)JSON.parse on block bodySame rules as backtick fences
Bare {…} in proseBare object candidateJSON.parse required to passOnly shown if valid; quoted spans and URLs skipped
Bare […] in proseBare array candidateJSON.parse required to passSame rules as bare object
Invalid JSON in fenceFenced block (invalid)Fails JSON.parseShown with ⚡ Quick Fix button + error + line/col; Format disabled
YAML or XML blockNot detectedNon-JSON fences ignored; bare YAML/XML does not start with { or [
JSON inside quoted stringNot detectedScanner skips quoted spans ≤300 chars
JSON inside URLNot detectedScanner skips http/https spans to end of line
JSON Schema (has $schema / type+properties)Fenced or bare candidate + Schema hintJSON.parse required to passSchema badge + link to JSON Schema Validator shown automatically
JSONC (// comments, trailing commas)Invalid candidate (strict) / Valid candidate (lenient)Fails strict JSON.parse; passes with Lenient modeEnable Lenient mode or use ⚡ Quick Fix to strip comments and commas

ToolsSonic Prompt JSON Formatter vs Competitors

FeatureToolsSonic
Prompt JSON Formatter
JSONFormatter.ioVS CodeOpenAI Playground
Accepts full prompt (prose + JSON)✅ Yes❌ Errors on prose❌ JSON files only⚠ Textarea only
Auto-detects JSON candidates in text✅ 2-pass scanner❌ No❌ No❌ No
Surrounding prose preserved exactly✅ Yes❌ N/A❌ No❌ No
Syntax-highlighted output✅ Yes — 6-type tokenizer✅ Yes✅ Yes❌ No
Collapsible JSON tree view✅ Yes — inline tab✅ Some variants✅ Extension❌ No
Before/after diff view✅ Yes — tab❌ No❌ No❌ No
Quick Fix (strip comments + trailing commas)✅ Yes — per-candidate button❌ No⚠ Extension❌ No
Lenient / JSONC mode✅ Yes — toggle❌ No⚠ With extension❌ No
Format all JSON blocks in one pass✅ Yes — "Format all valid"❌ No❌ No❌ No
Token count per candidate✅ Yes — compact estimate on each card❌ No❌ No✅ Yes
Copy as escaped string✅ Yes❌ No❌ No❌ No
JSON Schema auto-detection hint✅ Yes — links to validator❌ No❌ No❌ No
100% local — no server, no account✅ Yes⚠ Varies✅ Yes❌ Sends to OpenAI
100% private — runs in your browser Instant — no server round-trip Free forever — no account needed