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
# 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.jsonFormats
| Function | What it does |
|---|---|
| @json / tojson | Serialize value to a JSON string |
| fromjson | Parse a JSON string to a value |
| -c | Compact 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".