Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions parser/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ type Parser struct{}

// Unmarshal unmarshals JSON files.
func (p *Parser) Unmarshal(data []byte, v interface{}) error {
if len(data) > 2 && data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf {
data = data[3:] // Strip UTF-8 BOM, see https://www.rfc-editor.org/rfc/rfc8259#section-8.1
}

if err := json.Unmarshal(data, v); err != nil {
return fmt.Errorf("unmarshal json: %w", err)
}
Expand Down
42 changes: 42 additions & 0 deletions parser/json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,45 @@ func TestJSONParser(t *testing.T) {
t.Error("there should be at least one item defined in the parsed file, but none found")
}
}

func TestJSONParserWithBOM(t *testing.T) {
tests := []struct {
name string
input []byte
want map[string]any
wantErr bool
}{
{
name: "valid JSON with BOM",
input: append([]byte{0xEF, 0xBB, 0xBF}, []byte(`{"test": "value"}`)...),
want: map[string]any{"test": "value"},
},
{
name: "valid JSON without BOM",
input: []byte(`{"test": "value"}`),
want: map[string]any{"test": "value"},
},
}

parser := &Parser{}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got interface{}
err := parser.Unmarshal(tt.input, &got)
if (err != nil) != tt.wantErr {
t.Errorf("Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && got == nil {
t.Fatal("expected parsed content, got nil")
}
if m, ok := got.(map[string]any); ok {
for k, want := range tt.want {
if got := m[k]; got != want {
t.Errorf("key %q = %v, want %v", k, got, want)
}
}
}
})
}
}
Loading