Skip to content

Commit 7d59b14

Browse files
committed
json5: accept 'comment' fields in all JSON files
One complaint about the JSON5 format was that it has bad editor support. Well, actually no editor support. Any valid JSON is valid JSON5 so you basically can use JSON as the definition format for tests and suites, unfortunately you loose the ability to add comments. In traditional JSON this is done by ignored fields, often just named 'comment'. Unfortiunately the JSON5 decoder failes on unknown fields in a struct to prevent ugly and hard to track bugs from typos. This CL deliberately allows 'comment' everywhere in a JSON5 and won't fail if the struct to unmarshal to has no such field. Such comments are just ignored.
1 parent b01f796 commit 7d59b14

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

internal/json5/decode.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import (
3131
// b) If a JSON field cannot be mapped to a field in a Go struct
3232
// an error is created (the stdlib json silently ignores this
3333
// fact). The error is of type &UnmarshalUnknownFieldError.
34+
// There is one excpetion to this rule: A JSON5 field named
35+
// "comment" is allowed everywhere and ignored.
3436
// So this Unmarshal provides 'strict' unmarshaling.
3537
//
3638
// Unmarshal uses the inverse of the encodings that
@@ -598,11 +600,16 @@ func (d *decodeState) object(v reflect.Value) {
598600
subv = subv.Field(i)
599601
}
600602
} else {
601-
d.saveError(&UnmarshalUnknownFieldError{
602-
typ: v.Type().Name(),
603-
field: string(key),
604-
Offset: int64(start),
605-
})
603+
// Field is unknown in struct. Stdlib json ignores it.
604+
// We fail as this probably is a typo. But we do
605+
// ignore comments.
606+
if !bytes.Equal(key, []byte("comment")) {
607+
d.saveError(&UnmarshalUnknownFieldError{
608+
typ: v.Type().Name(),
609+
field: string(key),
610+
Offset: int64(start),
611+
})
612+
}
606613
}
607614
}
608615

internal/json5/decode_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ var unmarshalTests = []unmarshalTest{
235235
{in: `{"x": 1}`, ptr: new(tx), out: tx{},
236236
err: &UnmarshalUnknownFieldError{"tx", "x", 1}},
237237
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
238+
{in: `{"F1":1,"comment":"foo","F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
238239
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
239240
{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64},
240241
{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true},

0 commit comments

Comments
 (0)