hashicorp / hashicorp/hcl

Can't decode into map[string]interface{}

Open
#291 11 comments 4 reactions 0 assignees View on GitHub
enhancement gohcl v2
Dominant language
Go
Stars
5.8k
Forks
657
Avg merge
20h 36m
Merged PRs (30d)
6

Description

I've been experimenting with the `hcl2` code for use with Terragrunt, and so far, things have been going well. The parser is intuitive, the error messages are helpful, and the first-class support for expressions, functions, variables, etc is great! A big improvement over the original hcl code 👍

The one issue I'm hitting is when trying to use `Decode` function with the following struct:

```go
type Example struct {
Foo string `hcl:"foo,attr"`
Bar map[string]interface{} `hcl:"bar,attr"`
}
```

I try to decode it as follows:

```go
parser := hclparse.NewParser()
file, diagnostics := parser.ParseHCL([]byte(myConfig), "test")

if diagnostics.HasErrors() {
panic(diagnostics)
}

var example Example
diags := gohcl.DecodeBody(file.Body, nil, &example)
if diags.HasErrors() {
panic(diags)
}
```

I get the following error:

```
panic: unsuitable DecodeExpression target: no cty.Type for interface {} [recovered]
```

The `Bar` field of the `Example` struct is intentionally a `map[string]interface{}` because this is data that is user provided, and I have no way of knowing the types of the values; they could be strings, ints, bools, slices, maps, etc. I could parse this as a `block` and use the `remain` metadata to get back `hcl.Body`, but that requires changing the `Example` struct in a way that (a) is backwards incompatible, (b) leaks the underlying implementation details, and (c) is hard to use.

Is there any way to decode into a `map[string]interface{}` directly?

Contributor guide

No contributing guide indexed for this repository

Research direction

Start at gohcl.DecodeBody and the DecodeExpression path, reproducing the Example with hclparse.NewParser and ParseHCL. Compare the current interface{} diagnostic with the requested map[string]interface{} behavior; done means the example decodes user-provided strings, numbers, booleans, slices, and maps without that error.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.