Skip to content
Latchkey

jq @json and tojson : Serialize to a String

jq @json (and tojson) turns a value into a JSON-encoded string; fromjson parses a JSON string back into a value.

Embedding a JSON object inside another string, like a single line for $GITHUB_OUTPUT, needs tojson so the inner JSON is escaped correctly.

What it does

@json and tojson serialize the input to a JSON-encoded string, escaping quotes and special characters. fromjson does the reverse, parsing a JSON string that arrived as text inside another field. They are essential when JSON is nested inside JSON.

Common usage

Terminal
# emit a compact matrix value for an output
echo "matrix=$(jq -c '{include: map({name: .name})} ' tags.json)" >> "$GITHUB_OUTPUT"
# serialize a sub-object to a string field
jq '{config: (.config | tojson)}' settings.json
# parse a JSON string stored in a field
jq '.payload | fromjson' webhook.json

Formats

FunctionWhat it does
@json / tojsonSerialize value to a JSON string
fromjsonParse a JSON string to a value
-cCompact one-line JSON for outputs
ascii@json output is ASCII-safe

In CI

When writing JSON to $GITHUB_OUTPUT it must be a single line, so use -c on the top-level program and tojson for any nested JSON-in-a-string field. A later step reads it back with fromjson.

Common errors in CI

"jq: error (at <stdin>:0): Invalid literal" or "Cannot parse" from fromjson means the field held text that was not valid JSON; the upstream value was already decoded or truncated. tojson never fails on valid jq values but will serialize null as the string "null".

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →