Inferensys

Prompt

JSON Lines Record Separation Repair Prompt

A practical prompt playbook for using JSON Lines Record Separation Repair Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the repair job, the operator who runs it, and the pipeline conditions that make this prompt the right tool.

This prompt is for data pipeline operators and backend engineers who receive JSON Lines (JSONL/NDJSON) outputs from language models that have broken record boundaries. The core job is to reconstruct valid line-delimited JSON when the model merges multiple records onto one line, omits newline separators, produces partial lines, or interleaves non-JSON text with valid records. The prompt expects a raw, malformed text blob and returns clean, separated JSON records with a verified record count. It is not a general JSON repair tool—use the JSON Repair Prompt Template for API Payloads for single-object structural fixes, and use the Streaming Fragment Assembly Prompt when you are reassembling chunks from a real-time stream rather than repairing a complete but corrupted batch output.

Use this prompt when your pipeline has already received a complete model response but the JSONL parser rejects it due to line-boundary errors. Typical failure signals include: a JSONL parser returning fewer records than expected, JSONDecodeError on lines that contain multiple concatenated objects, or validation checks that find records with fields from adjacent records merged in. The prompt requires the raw corrupted output as [MALFORMED_JSONL] and the expected record count as [EXPECTED_COUNT]. It works best when the underlying JSON objects are individually valid but incorrectly separated—if the JSON objects themselves are malformed, run the Broken JSON Object Recovery Prompt first, then feed the repaired objects into this separation prompt. Do not use this prompt for streaming data where you lack the complete payload, or for formats other than JSONL/NDJSON.

Before wiring this into an automated pipeline, test it against your three most common failure patterns: merged records (two complete JSON objects on one line), missing newlines (a single line with many concatenated objects), and partial trailing records (a truncated final object). Measure whether the output record count matches [EXPECTED_COUNT] and whether each line parses as valid JSON independently. If the model consistently fails to separate records with high accuracy, consider adding a structural validation step that counts opening and closing braces to detect boundaries before calling the repair prompt, or escalate to human review when the confidence score drops below your pipeline's threshold.

PRACTICAL GUARDRAILS

Use Case Fit

Where the JSON Lines Record Separation Repair Prompt works and where it introduces unacceptable risk. Use this to decide whether to apply the prompt, add a pre-processing step, or escalate to application-level logic.

01

Good Fit: Streaming Pipeline Glue

Use when: A streaming JSONL producer (model or service) occasionally concatenates records due to a dropped newline. Guardrail: Run the repair prompt as a stateless map step in the stream processor, with a hard limit on input size per call to avoid unbounded context growth.

02

Good Fit: Batch File Sanitization

Use when: A nightly batch job produces a JSONL file that fails jsonlines library validation with 'line N is not valid JSON'. Guardrail: Split the file into chunks of 50-100 lines before repair to keep the prompt focused and prevent the model from rewriting the entire file.

03

Bad Fit: Semantic Deduplication

Avoid when: The problem is duplicate records with slightly different text, not broken line boundaries. Guardrail: Use a separate deduplication prompt or a deterministic hash-based dedup step before this repair prompt. Record separation repair should not change record content.

04

Bad Fit: Schema Validation Failures

Avoid when: Individual JSON objects are valid JSON but fail a downstream schema check (wrong types, missing fields). Guardrail: Route to a schema repair prompt instead. This prompt only fixes line boundaries and concatenation; it should not alter field values or types.

05

Required Input: Record Count Verification

Risk: The model may silently drop a partial record at the end of a chunk or invent a record to satisfy an expected count. Guardrail: Always pass the expected record count as [EXPECTED_COUNT] in the prompt and validate the output line count deterministically before accepting the repair.

06

Operational Risk: Large Payload Corruption

Risk: A single large JSON object split across multiple lines can be misinterpreted as multiple broken records, causing the model to restructure data incorrectly. Guardrail: Pre-scan input for objects exceeding a size threshold and route them to a dedicated large-object handler instead of the general repair prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for repairing broken JSON Lines (JSONL/NDJSON) files where record boundaries are corrupted.

This template is designed to be copied directly into your prompt management system, test suite, or application code. It instructs the model to act as a data recovery specialist, reconstructing valid line-delimited JSON from a malformed input. The prompt uses square-bracket placeholders for all dynamic inputs, ensuring you can swap in different files, schemas, and constraints without rewriting the core instruction. The primary goal is to recover as many complete records as possible while explicitly flagging any data that is unrecoverable.

text
You are a precise data repair system. Your task is to repair a malformed JSON Lines (JSONL) file.

**Input:**
The input is provided in the [INPUT] section below. It is intended to be a valid JSONL file, but record boundaries are broken. Common issues include:
- Multiple JSON objects on a single line.
- A single JSON object split across multiple lines.
- Missing newline characters between records.
- Empty or whitespace-only lines.

**Instructions:**
1.  Parse the [INPUT] and identify all complete, valid JSON objects.
2.  Reconstruct the file so that each valid JSON object is on its own line, separated by a single newline character.
3.  Do not modify the internal structure, key names, or values of any valid JSON object you recover.
4.  If you encounter text fragments that cannot be assembled into a complete, parseable JSON object, do not guess or hallucinate data. Instead, append them as a single escaped string on a new line, prefixed with the marker [UNRECOVERABLE_FRAGMENT].
5.  If a [TARGET_SCHEMA] is provided, validate each recovered record against it. Append any records that fail validation as a string on a new line, prefixed with the marker [SCHEMA_VIOLATION], followed by the original JSON object and the validation error.

**Constraints:**
- [CONSTRAINTS]

**Output Format:**
Output ONLY the repaired JSONL content inside a single fenced code block with the language tag `jsonl`.

**Input Data:**
[INPUT]

**Target Schema (Optional):**
[TARGET_SCHEMA]

To adapt this template, replace the placeholders with your specific context. The [INPUT] placeholder should contain the raw, corrupted text. Use the [CONSTRAINTS] placeholder to add rules like a maximum number of records or a specific sorting order. The [TARGET_SCHEMA] is optional; if provided, it should be a valid JSON Schema object. If you don't have a schema, remove that entire instruction block. For high-stakes data pipelines, always follow this automated repair with a manual review step for any records flagged as [UNRECOVERABLE_FRAGMENT] or [SCHEMA_VIOLATION] to prevent data loss or corruption from propagating downstream.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the JSON Lines Record Separation Repair Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[CORRUPTED_JSONL]

The malformed JSON Lines content requiring repair—may contain merged records, missing newlines, or partial lines

{"id":1}{"id":2}{"id":3,"name":"incomplete

Must be a non-empty string. Check for presence of at least one '{' character. Null or empty input should short-circuit with an empty result, not invoke the model.

[EXPECTED_RECORD_COUNT]

The known or estimated number of complete JSON objects that should exist in the valid output

150

Must be a positive integer or null. When null, the prompt should skip record-count verification and rely only on structural repair. When provided, use as a completeness gate after repair.

[RECORD_SCHEMA]

Optional JSON Schema describing the expected shape of each record, used to validate repaired objects

{"type":"object","required":["id","timestamp"]}

Must be a valid JSON Schema object or null. When provided, each repaired record must pass schema validation. When null, skip per-record schema checks and validate only that each line is parseable JSON.

[FIELD_DELIMITER_HINT]

Clue about what character or pattern separates records when newlines are missing—helps the model find record boundaries

"}{"

Must be a string or null. Common values: '}{"', '}\n{', '},{'. When null, the model must infer boundaries from structural analysis alone. Invalid hints may cause incorrect splitting; log when hint is used.

[MAX_RECORD_SIZE_BYTES]

Upper bound on expected record size, used to detect merged records that exceed normal length

4096

Must be a positive integer or null. When set, records exceeding this size after repair should be flagged for review. Use to catch under-split records. Null disables size-based anomaly detection.

[TRUNCATION_POLICY]

Instruction for handling the final record if it appears incomplete—either 'drop', 'repair_best_effort', or 'flag'

"flag"

Must be one of: 'drop', 'repair_best_effort', 'flag'. 'drop' removes the partial record. 'repair_best_effort' attempts to close braces and quotes. 'flag' keeps the partial record with a warning field appended. Invalid values should default to 'flag' with a logged warning.

[OUTPUT_VALIDATOR_ENDPOINT]

Optional callback URL or function name for post-repair validation—used in automated pipelines to trigger downstream checks

Must be a valid URL string or null. When provided, the repair harness should POST the repaired output to this endpoint and check the response before returning. Null means validation is caller's responsibility. Do not pass to the model; this is a harness-level variable.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the JSON Lines Record Separation Repair Prompt into a production data pipeline with validation, retries, and record count verification.

The JSON Lines repair prompt is designed to sit inside a post-generation validation loop, not as a standalone one-shot call. When your pipeline receives a model output that fails JSONL parsing—typically because record boundaries are missing, merged, or truncated—this prompt becomes the recovery path. The harness should catch parse errors, extract the raw text and the expected record count, and invoke the repair prompt with both. Do not call the repair prompt on every output; gate it behind a parse attempt so you only pay the latency and token cost when repair is actually needed.

The implementation loop follows a clear sequence: (1) Attempt to parse the raw output with a streaming JSONL parser that can report the line number and character offset of the first failure. (2) If parsing succeeds, validate that the parsed record count matches the expected count from your upstream request. (3) On failure, construct the repair prompt call with [RAW_OUTPUT] set to the full model response text and [EXPECTED_RECORD_COUNT] set to the number of records you requested. (4) Parse the repair prompt's response, which should be valid JSONL. (5) Re-validate record count. If the repair output still fails, log the failure, increment a repair-attempt counter, and either retry once with a slightly different temperature or escalate to a dead-letter queue for human review. Never loop more than twice—diminishing returns set in fast, and infinite retry loops on malformed data will burn tokens and block your pipeline.

For validation, use a strict JSONL parser that rejects lines that aren't valid JSON objects. After parsing, run a record count check: len(records) == expected_count. Also verify that each record is a JSON object (not an array, string, or number) unless your schema permits top-level scalars. Log the repair rate as a metric—what percentage of outputs require repair—so you can detect model drift or prompt degradation over time. If the repair rate spikes above 5-10%, investigate whether your generation prompt is producing consistently broken boundaries and fix the root cause rather than relying on the repair harness indefinitely.

Model choice matters here. The repair task is structural, not creative, so prefer models with strong instruction-following and JSON manipulation capabilities. Temperature should be set low (0.0–0.1) to maximize deterministic repair behavior. If you're using a model that supports structured output modes, you can request that the repair response itself be valid JSONL, but the prompt template already instructs the model to output only the repaired records with no markdown fences or commentary. Parse the response by stripping leading/trailing whitespace and feeding each line through JSON.parse (or equivalent). Reject any response that contains markdown fences, explanatory text, or a different number of lines than expected.

Wire this into your observability stack. Log every repair attempt with: the original parse error message, the byte offset of the failure, the expected vs. actual record count before repair, the repair prompt's token usage, and the post-repair validation result. This data lets you distinguish between transient boundary issues (one-off newline drops) and systemic failures (the model consistently merges the last two records). If you see systemic patterns, fix the generation prompt or adjust your output parsing to be more tolerant before reaching for repair. The repair prompt is a safety net, not a substitute for reliable generation.

IMPLEMENTATION TABLE

Expected Output Contract

The repair prompt must produce a single valid JSON Lines document. Each row below defines one required property of the output. Use this contract to build a post-processing validator before the repaired output enters any downstream pipeline.

Field or ElementType or FormatRequiredValidation Rule

repaired_jsonl

String (newline-delimited JSON)

Must parse as one JSON object per line; no blank lines; no trailing newline required but allowed

record_count

Integer

Must equal the number of lines in repaired_jsonl; must match [EXPECTED_RECORD_COUNT] if provided

repair_log

Array of objects

Each entry must contain line (integer), issue (string from allowed set), action (string), and confidence (float 0-1)

repair_log[].issue

String enum

Allowed values: merged_records, missing_newline, partial_record, truncated_line, empty_line, encoding_artifact

repair_log[].confidence

Float

Must be between 0.0 and 1.0 inclusive; values below [CONFIDENCE_THRESHOLD] should trigger human review flag

unrecoverable_lines

Array of integers

Line numbers that could not be repaired; empty array if all lines recovered; must not overlap with repaired lines

structural_integrity

Object

Must contain keys: balanced_brackets (boolean), consistent_delimiters (boolean), valid_utf8 (boolean); all must be true for output to pass

repair_summary

String

Must describe total lines processed, lines repaired, lines unrecoverable, and overall confidence; no markdown; max 500 characters

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when repairing JSON Lines record separation and how to guard against it.

01

Merged Records Without Delimiters

What to watch: The model concatenates multiple JSON objects into one line without newline separators, creating a single unparseable blob. This happens when the model treats JSONL as a continuous stream rather than line-delimited records. Guardrail: Pre-process the output with a regex that splits on }{ boundaries and re-inserts newlines. Validate that each resulting line parses as independent JSON before accepting the repair.

02

Partial or Truncated Final Record

What to watch: The last record in the sequence is cut off mid-object due to token limits or streaming interruption, leaving an unclosed brace and incomplete key-value pairs. Guardrail: Detect unclosed braces at end-of-output. Attempt structural close by counting open/close bracket depth. If depth > 0, either request continuation with the partial record as context or discard the incomplete record and log a truncation event with the original payload.

03

Embedded Newlines Inside String Values

What to watch: Legitimate newline characters inside JSON string values break line-by-line parsing, causing parsers to treat one record as multiple malformed lines. Guardrail: Use a streaming JSON parser that respects string boundaries rather than naive line splitting. If using line-based splitting, validate that each split segment is valid JSON before processing. Flag records where string values contain unescaped control characters.

04

Record Count Mismatch After Repair

What to watch: The repair process silently drops or duplicates records, producing a different record count than expected. Downstream consumers relying on exact counts will produce incorrect results. Guardrail: Require an [EXPECTED_RECORD_COUNT] input parameter. After repair, count valid parsed records and compare. On mismatch, either fail with a count discrepancy error or output a repair audit showing which records were added, removed, or merged. Never silently accept count drift.

05

Whitespace-Only Lines Between Records

What to watch: Empty lines or whitespace-only lines between valid JSON records cause some strict JSONL parsers to reject the entire file. Models sometimes insert blank lines for readability. Guardrail: Strip empty and whitespace-only lines during pre-processing before attempting JSON parsing. Log the number of stripped lines in the repair audit. Validate that the cleaned output contains only non-empty JSON lines.

06

Inconsistent Record Shape Across Lines

What to watch: Repaired records have different keys, missing required fields, or inconsistent value types compared to the expected schema. The repair fixes structural JSONL issues but introduces semantic inconsistency. Guardrail: After structural repair, validate each record against a [RECORD_SCHEMA]. Flag records that fail schema validation separately from records that failed structural parsing. Output a per-record status: valid, repaired-structurally, repaired-with-schema-gaps, unrecoverable.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the JSON Lines Record Separation Repair Prompt before deployment. Each row defines a pass standard, a failure signal, and a concrete test method to validate output quality.

CriterionPass StandardFailure SignalTest Method

Record Boundary Reconstruction

Output contains exactly [EXPECTED_RECORD_COUNT] valid JSON objects, each on its own line

Output line count differs from [EXPECTED_RECORD_COUNT] or any line fails JSON.parse

Count lines in output; parse each line with JSON.parse; assert line count equals [EXPECTED_RECORD_COUNT]

Merged Record Separation

No single output line contains more than one JSON object or concatenated object fragments

Any line contains multiple top-level braces or a trailing brace followed by content on same line

Regex scan for }{ pattern on single line; flag any line where JSON.parse succeeds but contains unexpected sibling keys

Partial Line Completion

Truncated final record is either completed with valid closing braces or flagged with [TRUNCATION_FLAG] field

Output ends with unclosed braces, missing closing bracket, or unterminated string

Parse final line with JSON.parse; if parse fails, check for [TRUNCATION_FLAG] key; assert either valid parse or flag present

Content Preservation

All key-value pairs from [INPUT_JSONL] appear in output records with identical values and no hallucinated fields

Output records contain extra keys not present in input, missing keys, or altered values

For each output record, identify corresponding input record by [RECORD_ID_FIELD]; deep-equal compare key sets and values; flag additions or omissions

Newline Character Normalization

All output lines end with a single newline character (\n) with no carriage returns or double newlines

Output contains \r\n sequences, blank lines between records, or trailing whitespace before newline

Inspect raw bytes of output; assert no \r characters present; assert no empty lines; assert each line ends with exactly one \n

Encoding Integrity

Output is valid UTF-8 with no replacement characters, mojibake, or byte-order marks

Output contains U+FFFD replacement characters, non-UTF-8 byte sequences, or BOM prefix

Validate output with UTF-8 decoder; scan for U+FFFD; check first byte is not BOM (0xEF 0xBB 0xBF); assert clean decode

Idempotency Under Repair

Running the repair prompt on its own valid output produces identical output with zero changes

Second repair pass modifies records, reorders fields, or changes whitespace

Feed repaired output back through prompt with same [EXPECTED_RECORD_COUNT]; assert output equals input byte-for-byte or record-for-record

Error Annotation Quality

Unrecoverable segments are replaced with [ERROR_RECORD] containing original text, error type, and byte offset

Unrecoverable segments are silently dropped, replaced with empty object, or annotated without byte offset

Search output for [ERROR_RECORD] keys; assert each contains original_text, error_type, and byte_offset fields with non-null values

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single pass and manual inspection. Accept best-effort repair without strict record count verification. Run on a small sample of broken JSONL before scaling.

Watch for

  • Merged records that the model splits incorrectly
  • Partial lines silently dropped
  • No validation that output line count matches expected record count
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.