hashicorp / hashicorp/hcl

BUG: JSON decodes array of structs wrong

Open
#209 5 comments 10 reactions 0 assignees View on GitHub
v1
Dominant language
Go
Stars
5.8k
Forks
657
Avg merge
20h 36m
Merged PRs (30d)
6

Description

The JSON parser of the hcl package decodes two elements for the inner array instead of one:

```json
{"x":[{"a":1, "b":2}]}
```

Here is the Go test to verify this:

```go
// === RUN TestArrayWithStruct
// === RUN TestArrayWithStruct/encoding/json
// === RUN TestArrayWithStruct/hashicorp/hcl
// --- FAIL: TestArrayWithStruct (0.00s)
// --- PASS: TestArrayWithStruct/encoding/json (0.00s)
// --- FAIL: TestArrayWithStruct/hashicorp/hcl (0.00s)
// main_test.go:38: got main.Y{X:[]main.X{main.X{A:1, B:0}, main.X{A:0, B:2}}} want main.Y{X:[]main.X{main.X{A:1, B:2}}}
func TestArrayWithStruct(t *testing.T) {
type X struct {
A, B int
}
type Y struct {
X []X
}

j := `{"x":[{"a":1,"b":2}]}`
y := Y{X: []X{{A: 1, B: 2}}}
t.Run("encoding/json", func(t *testing.T) {
var v Y
if err := json.Unmarshal([]byte(j), &v); err != nil {
t.Fatalf("got error %v want nil", err)
}
if got, want := v, y; !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v want %#v", got, want)
}
})
t.Run("hashicorp/hcl", func(t *testing.T) {
var v Y
if err := hcl.Decode(&v, j); err != nil {
t.Fatalf("got error %v want nil", err)
}
if got, want := v, y; !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v want %#v", got, want)
}
})
}
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by running the provided Go TestArrayWithStruct reproduction against hcl.Decode and inspect the HCL JSON decoding path it exercises. The fix is done when the array contains one struct with both A and B populated and the regression test passes.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.