Convert a Basic HCL Block to JSON
Learn how a simple HCL block with attributes translates to a JSON object. Covers string, number, boolean values and the fundamental block-to-object mapping.
Detailed Explanation
From HCL Block to JSON Object
The most fundamental conversion takes an HCL block and produces a JSON object. Each attribute in the block becomes a key-value pair in the JSON object, and the block type and labels determine the nesting structure.
Example HCL
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
count = 3
monitoring = true
}
Generated JSON
{
"resource": {
"aws_instance": {
"web": {
"ami": "ami-0c55b159cbfafe1f0",
"instance_type": "t2.micro",
"count": 3,
"monitoring": true
}
}
}
}
Key Mapping Rules
| HCL element | JSON equivalent |
|---|---|
| Block type | Top-level key |
| Block labels | Nested object keys |
| String attribute | JSON string |
| Number attribute | JSON number |
| Boolean attribute | JSON boolean |
null |
JSON null |
Block Label Nesting
HCL blocks with labels create nested JSON objects. A resource "type" "name" block produces three levels of nesting: the block type key, the resource type key, and the resource name key. This mirrors Terraform's JSON configuration syntax where labels become object keys.
Type Preservation
HCL's type system maps cleanly to JSON: strings remain strings, integers and floats become JSON numbers, and booleans map directly. The null keyword converts to JSON null. This makes the conversion lossless for primitive types.
Use Case
When you need to understand the fundamental relationship between HCL configuration blocks and their JSON equivalents, such as when starting to work with Terraform's JSON configuration syntax (.tf.json files) or building tooling that generates Terraform configurations programmatically.