Introduction
This article explains how to produce a minified JSON string from a multi-line or formatted JSON source within your Terraform configuration.
Use Case
When you use a multi-lined JSON string with certain APIs, such as the AWS API, the request may fail due to unexpected whitespace. Minifying the JSON string by removing line breaks and extra spaces ensures it is in a format that the API can parse correctly.
Procedure
Since Terraform 0.12, you can produce minified JSON by using a round-trip expression with the jsondecode and jsonencode functions. The jsonencode function always produces a compact, single-line JSON string.
If a data source or resource attribute provides a JSON string that is not minified, you can use the expression jsonencode(jsondecode(data.some_data_source.json)) to minify it.
Example
This example demonstrates how to convert a multi-line JSON string into a minified version.
-
Define a variable containing a multi-line JSON string and create two outputs: one for the original string and one for the minified version.
variable "json_text" { type = string default = <<EOF { "foo": "bar", "baz": [ "qux" ] } EOF } output "not_minified" { value = var.json_text } output "minified" { value = jsonencode(jsondecode(var.json_text)) } -
Apply the configuration.
$ terraform apply -auto-approve
-
Review the output. The
minifiedoutput contains the compact, single-line JSON string, while thenot_minifiedoutput preserves the original formatting.Outputs: minified = "{\"baz\":[\"qux\"],\"foo\":\"bar\"}" not_minified = <<EOT { "foo": "bar", "baz": [ "qux" ] } EOT
By using jsonencode, you can also leverage the full Terraform expression language, which permits features not available in standard JSON, such as comments, trailing commas, and for expressions for dynamic object construction.
Additional Information
- For more details on the
jsonencodefunction, please refer to the Terraform documentation.