You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform jsondecode函数未将JSON字符串null转为Terraform空值

问题解析与解决办法

为什么会出现这个差异?

你输入的JSON里"null"是字符串字面量,不是JSON规范里的原生null值。Terraform的jsondecode严格遵循JSON语法,所以会把带引号的"null"解析成Terraform的字符串类型,而不是null值。只有当JSON里写不带引号的null时,才会被解析为Terraform的null。

解决办法

方法1:修正JSON文件(推荐)

如果能控制JSON文件的内容,直接把字符串"null"改成JSON原生的null:

{"hello": null}

用jsondecode处理这个JSON,就能得到你期望的{"hello" = null}。

方法2:在Terraform中额外转换

如果无法修改JSON源,需要在Terraform里对解析后的值做判断转换:

locals {
  json_data = jsondecode("{\"hello\": \"null\"}")
  processed_data = {
    hello = local.json_data.hello == "null" ? null : local.json_data.hello
  }
}

output "result" {
  value = local.processed_data
}

这样输出的result就是{"hello" = null}。

适配JSON文件定义变量的场景

如果是通过JSON文件定义Terraform变量,直接在JSON文件中使用原生null即可。比如变量文件variables.tfvars.json:

{
  "my_var": null
}

Terraform会自动将其解析为null值,不需要额外用jsondecode(除非你是手动读取JSON文件内容再解析)。

内容的提问来源于stack exchange,提问作者vroomvroom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:31:08