Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

Custom Templates for JSON Output Formatting

If you need JSON to come out in a very specific shape, what you usually want is not just pretty-printing. You want a custom output template: a rule that says which fields to keep, what to rename, how to flatten nested data, what defaults to use, and which computed values should appear in the final result.

That can be as simple as mapping a few keys or as strict as generating a contract-ready payload for another API. The important distinction is this: a formatter improves readability, while a template or transformation changes the structure itself. For search visitors landing here directly, the fastest path is to define the exact output you want first, then choose the lightest tool that can produce it reliably.

What Counts as a JSON Output Template?

In practice, a JSON template is any repeatable rule that turns input JSON into a different output shape. That usually includes one or more of these actions:

  • Whitelisting fields: keep only the properties the receiving system actually needs.
  • Renaming keys: convert names like `userId` to `user_id` or `id`.
  • Flattening nested data: pull values from deep objects into a simpler top-level shape.
  • Adding defaults: output `null`, `[]`, or a fallback string when a field is missing.
  • Computing new values: combine fields, calculate labels, or emit counts.
  • Reshaping arrays: turn large objects into compact lists of records.

The cleanest custom templates are declarative: they describe the output structure directly. Once the logic becomes highly conditional, code is usually easier to test and maintain than a dense expression.

Choose the Right Approach

Different tools fit different jobs. If your current workflow is unclear, use this rule of thumb:

Use jq for CLI work, scripts, and pipelines

jq is strong when you are transforming JSON in shell scripts, CI jobs, exports, or log-processing flows. It is concise, composable, and built around constructing new JSON objects from existing input.

Use JSONata for declarative templates inside apps or integrations

JSONata is a good fit when you want expressions that look close to the target output shape and need a reusable transformation language rather than custom application code.

Use JavaScript or Python when logic needs tests and branching

If you need validation, multiple fallback rules, date parsing, schema checks, or business rules, regular code is usually the most maintainable option.

Version differences matter. As of March 11, 2026, the jq site lists binary downloads for jq 1.8.1, and the JSONata documentation is published as version 2.1.0. If you are working inside a hosted integration platform or an embedded library, check its exact runtime before copying expressions from the latest docs.

Start With the Output Sample

The easiest way to avoid messy templates is to write the desired output first. This removes ambiguity and makes the mapping obvious.

  1. Write a realistic example of the exact JSON you want to emit.
  2. Annotate where each output field comes from in the input.
  3. Decide how missing values should behave: fail, drop, or default.
  4. Only then choose jq, JSONata, or code.

Example Input

This sample includes common template tasks: nested fields, arrays, a boolean flag, and a value you may want to rename before sending elsewhere.

{
  "id": 42,
  "profile": {
    "firstName": "Ava",
    "lastName": "Lopez",
    "city": "Madrid"
  },
  "plan": {
    "name": "Pro",
    "renewal": "2026-04-01"
  },
  "active": true,
  "tags": ["beta", "team-admin"]
}

Example 1: jq Template-Style Filter

jq is often the fastest way to define a custom JSON output format on the command line. The filter below builds a new object explicitly, which makes it read like a lightweight template.

jq Filter

{
  user_id: .id,
  full_name: (.profile.firstName + " " + .profile.lastName),
  city: .profile.city,
  plan: .plan.name,
  renews_on: .plan.renewal,
  status: (if .active then "active" else "inactive" end),
  tags: (.tags // [])
}

Output

{
  "user_id": 42,
  "full_name": "Ava Lopez",
  "city": "Madrid",
  "plan": "Pro",
  "renews_on": "2026-04-01",
  "status": "active",
  "tags": ["beta", "team-admin"]
}

This pattern covers the majority of real-world template needs: selection, renaming, flattening, defaults, and a computed label. If your team works in shell scripts or CI, jq is hard to beat for this kind of transformation.

Example 2: JSONata Expression

JSONata is useful when you want the expression itself to resemble the final JSON structure. The official docs describe JSONata as a lightweight query and transformation language for JSON, and that is exactly why it works well for template-like output mapping.

JSONata Expression

{
  "user_id": id,
  "full_name": profile.firstName & " " & profile.lastName,
  "city": profile.city,
  "plan": plan.name,
  "renews_on": plan.renewal,
  "status": active ? "active" : "inactive",
  "tag_count": $count(tags)
}

JSONata is especially attractive when non-developers need to review or adjust mappings, because the output object is visible right in the expression. For deeply custom validation or side effects, application code is still the safer long-term choice.

Example 3: JavaScript Mapping Function

If the template needs branching, validation, or unit tests, a small function is often clearer than a dense query expression.

function formatUser(input) {
  return {
    user_id: input.id,
    full_name: `${input.profile?.firstName ?? ""} ${input.profile?.lastName ?? ""}`.trim(),
    city: input.profile?.city ?? null,
    plan: input.plan?.name ?? "free",
    renews_on: input.plan?.renewal ?? null,
    status: input.active ? "active" : "inactive",
    tags: Array.isArray(input.tags) ? input.tags : []
  };
}

The advantage here is maintainability. You can validate input types, reuse helpers, write tests for edge cases, and evolve the transformation without forcing complex business logic into a template language.

Common Template Patterns to Reuse

Most custom JSON output rules are combinations of a few recurring patterns:

  • Field whitelist: emit only the contract fields and nothing else.
  • Rename map: keep values but translate key names to the target convention.
  • Flatten nested objects: move deeply nested properties to the top level when the consumer expects a compact payload.
  • Default missing values: output consistent types so downstream code does not guess.
  • Derived fields: combine multiple inputs into a display label, slug, or status value.
  • Array mapping: transform each record into a smaller or standardized object before exporting.

Troubleshooting Custom JSON Templates

The failures are usually predictable. Build for them early instead of treating them as cleanup work.

  • Missing fields: decide explicitly whether to omit, default, or fail when input paths are absent.
  • Array surprises: confirm whether you should transform one record or every item in a list. Many template bugs come from accidentally applying an object rule to an array.
  • Type drift: keep output types stable. A field that is sometimes a string and sometimes an object will create downstream bugs quickly.
  • Unsafe string templating: do not hand-build JSON text when you can create native objects and serialize them safely.
  • Large payloads: for very large files, prefer streaming or CLI-based transformations over copying everything into a browser tab.

Practical Rule of Thumb

If your mapping fits on one screen and mostly renames or reshapes fields, a declarative template is usually the right answer. If you need business rules, validation, retries, date math, or extensive branching, switch to application code early. That keeps the transformation understandable for the next person who has to debug it.

Once you have the template in place, validate both the source JSON and the transformed output with a JSON formatter so you can catch syntax issues, missing commas, or accidental type changes before the payload moves downstream.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool