IBM Support

How to minify the output of JSON files

How To


Summary

This article explains how to produce a minified JSON string from a multi-line or formatted JSON source within your Terraform configuration.

Steps

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.

  1. 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))
    }
  2. Apply the configuration.

    $ terraform apply -auto-approve
  3. Review the output. The minified output contains the compact, single-line JSON string, while the not_minified output 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

Document Location

Worldwide

[{"Type":"MASTER","Line of Business":{"code":"LOB77","label":"Automation Platform"},"Business Unit":{"code":"BU048","label":"IBM Software"},"Product":{"code":"SSGH5YK","label":"IBM Terraform Self-Managed"},"ARM Category":[{"code":"a8mgJ0000000DyEQAU","label":"Terraform-\u003ECLI Configuration"}],"ARM Case Number":"","Platform":[{"code":"PF025","label":"Platform Independent"}],"Version":"1.0.0;1.0.1;1.0.2;1.0.3;1.1.0;1.1.1;1.1.2;1.1.3;1.1.4;1.2.0;1.2.1;1.2.2;2.0.0;2.0.1;2.0.2;2.0.3;2025.03;2025.04;2025.05;2025.06;2025.07"}]

Historical Number

4413462404243

Document Information

Modified date:
31 August 2026

UID

ibm17265667