Use variables and placeholders in JSON templates

JSON has no built-in variables. Learn how placeholder substitution works, where it breaks validity and escaping, and when to use plain JSON or a serializer instead.

Many teams keep a JSON file with slots for values that change, such as a service name, a port or an API key, and fill those slots before the file is used. This review explains what that substitution changes, where it breaks, and when a plain, fully rendered JSON document is the better choice.

Short verdict: is a placeholder template suitable for your use?

A placeholder template is a reasonable choice when one JSON shape is reused with a small number of varying values, for example per-environment configuration or repeated API request bodies. The main benefit is a single source for the structure. The decisive tradeoff is that the template is not the data: until it is rendered, it may not be valid JSON, it cannot be checked against a schema, and the substitution step can produce broken or unsafe output if values are not escaped for JSON.

Plain JSON is preferable when the values are fixed, when the file is shared with people or systems that expect to parse it directly, when it serves as documentation or a test fixture, and when the varying values come from untrusted input. In those cases, either store the final JSON or generate it with a JSON serializer rather than with text substitution.

What a JSON placeholder actually is

JSON itself has no variables, no expressions and no comments. The format defines objects, arrays, strings, numbers, true, false and null, and nothing else. Any "JSON variable" is therefore a convention added by a separate tool: a marker in the text, such as {{name}} or ${NAME}, that a templating engine, a shell utility or a script replaces with a value before the result is parsed.

Two things are often confused with placeholders. The "$ref" keyword in JSON Schema and similar specifications is a reference to another part of a document, resolved by tools that understand that specification; it is not a general-purpose variable. JSON Pointer is a syntax for addressing a location inside a document, not for inserting values. Neither turns ordinary JSON into a template.

What substitution changes in the stored text

Placeholder substitution is a change to the stored characters, not a visual effect. The engine finds each marker and writes the value's characters in its place. The rendered output is a different text from the template, and only the rendered output is what a JSON parser sees. Whether that output is valid depends on where the marker sat and how the value was escaped.

Where the marker sits matters most. If it is inside quotes, the template stays parseable, but every value becomes a string:

{
  "service": "{{service_name}}",
  "port": "{{port}}",
  "debug": "{{debug}}"
}

Rendering that template with port 8080 and debug false produces "8080" and "false" as strings, not as a number and a boolean. A consumer that expects types may reject them or silently coerce them. If the markers for non-string values are left unquoted, the rendered output can have the right types, but the template itself is no longer valid JSON, so editors and validators will flag it until it is filled in:

{
  "service": "{{service_name}}",
  "port": {{port}},
  "debug": {{debug}}
}

The escaping problem

Text substitution does not know it is writing JSON. A value that contains a double quote, a backslash or a line break must be escaped inside a JSON string, and a plain substitution will not do that. Inserting the value He said "hi" into "{{message}}" produces output that no JSON parser will accept:

{
  "message": "He said "hi""
}

The opposite mistake is also common. Mustache and Handlebars escape HTML by default with the double-brace form, so a value such as R&D can come out as R&D, which is valid JSON but the wrong data. Their triple-brace form disables that escaping, but it does not add JSON escaping either. Shell tools such as envsubst replace ${NAME} with the raw environment value and also perform no JSON escaping. When values come from users or external systems, the same gap allows a crafted value to close a string and inject extra keys, which makes unescaped substitution a correctness and a security concern.

Common placeholder approaches compared

Approach | Example marker | Is the template valid JSON? | Is JSON escaping handled?
Mustache or Handlebars, quoted marker | "{{name}}" | Yes, but every value is a string | No; default escaping targets HTML
Mustache or Handlebars, unquoted marker | {{port}} | No | No
Shell substitution (envsubst) | "${NAME}" | Yes if the marker is quoted | No
jq with --arg and --argjson | $name inside a jq filter | The filter is not JSON; the output is | Yes
Build the data and serialize it | No marker; values set in code | Not applicable | Yes

Safer ways to fill in values

The reliable pattern is to treat values as data and let a JSON-aware tool produce the text. With jq, --arg passes a value as a JSON string and --argjson passes a value that is parsed as JSON, so numbers and booleans keep their types and quotes are escaped:

jq -n --arg name 'billing "east"' --argjson port 8080 \
  '{service: $name, port: $port}'
{
  "service": "billing \"east\"",
  "port": 8080
}

In application code, the equivalent is to build a dictionary, object or map and pass it to the language's JSON serializer, such as json.dumps in Python or JSON.stringify in JavaScript. The structure can still live in one place as a function or a base object; only the values change, and the serializer handles quoting and escaping.

import json

values = {"service_name": 'billing "east"', "port": 8080}
print(json.dumps({"service": values["service_name"], "port": values["port"]}, indent=2))

If a text template is unavoidable, for example because a deployment tool requires one, keep markers only inside string values where possible, restrict the allowed characters in substituted values, and validate every rendered file before use.

Will the result stay usable after copying or sharing?

A rendered JSON file behaves like any other JSON once it is valid: it can be copied, pasted into a validator, diffed and parsed. The template is a different matter. Pasting a template with unquoted markers into a JSON formatter, linter or API client will usually produce a parse error, and a template with quoted markers will parse but may fail schema validation because of string-typed numbers and booleans. Anyone receiving the template also needs to know which engine and syntax it targets, since {{name}}, ${NAME} and $name mean different things to different tools.

Search and editing are affected in practical ways. Searching a repository for a real value will not find it in the template, and a reviewer reading the template cannot see the final types or content. Editor features that depend on parsing, such as folding, schema hints and auto-formatting, may stop working on templates that are not valid JSON.

A plain-text, fully rendered equivalent is needed whenever the JSON is shared with an external consumer, attached to a bug report, used as a test fixture or published as an example. No evidence was supplied about how specific editors, API clients or assistive technologies handle placeholder templates, so claims about any named destination should be confirmed with a scoped test in that environment rather than assumed from one successful rendering.

Checks before you rely on a rendered file

  • Parse the rendered output with a strict JSON parser; a nonzero exit or error means the substitution broke the structure.
  • Search the output for leftover markers such as {{ or ${ to catch values that were never supplied.
  • Confirm that numbers, booleans and null have the intended types rather than being quoted strings.
  • Test with values that contain quotes, backslashes, line breaks and non-ASCII characters.
  • Validate against a schema if the consumer has one, using the rendered file rather than the template.
jq empty rendered.json && ! grep -nE '\{\{|\$\{' rendered.json

Evidence gaps

This review relies on the structure of the JSON format and the commonly documented behavior of the tools named above. No measurements, benchmark results or tool-specific test reports were supplied. Exact behavior can differ between versions and configurations of templating engines, so check the documentation of the version you use and test with representative values before adopting a template workflow.