From 48f7cd2e7701dfce31e375821e567154448a2ab4 Mon Sep 17 00:00:00 2001 From: Quinn Slack Date: Fri, 2 Mar 2018 21:56:42 -0800 Subject: [PATCH] Parse: allow trailing commas in array (not just object) --- parser_test.go | 6 +++++- visitor.go | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/parser_test.go b/parser_test.go index 7e5a530..475c972 100644 --- a/parser_test.go +++ b/parser_test.go @@ -60,7 +60,6 @@ func TestParser(t *testing.T) { // array with errors "[,]": {want: "[]", errors: true}, - "[ 1, 5, ]": {want: "[1,5]"}, "[ 1, 2, ]": {options: &ParseOptions{TrailingCommas: false}, want: "[1,2]", errors: true}, "[ 1 2, 3]": {want: "[1,2,3]", errors: true}, "[ ,1, 2, 3 ]": {want: "[1,2,3]", errors: true}, @@ -76,8 +75,10 @@ func TestParser(t *testing.T) { `{ "hello": [] }`: {want: `{"hello":[]}`}, `{ "hello": [], "world": {}, }`: {want: `{"hello":[],"world":{}}`}, `{ "hello2": [], "world": {} }`: {want: `{"hello2":[],"world":{}}`}, + "[ 1, 5, ]": {want: "[1,5]"}, `{ "hello2": [], }`: {options: &ParseOptions{TrailingCommas: false}, want: `{"hello2":[]}`, errors: true}, `{ "hello2": [], "world": {}, }`: {options: &ParseOptions{TrailingCommas: false}, want: `{"hello2":[],"world":{}}`, errors: true}, + "[ 1, 6, ]": {options: &ParseOptions{TrailingCommas: false}, want: "[1,6]", errors: true}, } for input, test := range tests { label := fmt.Sprintf("%q", input) @@ -93,6 +94,9 @@ func TestParser(t *testing.T) { if test.errors && errors == nil { t.Errorf("%s: got no parse errors, want parse errors", label) } + if !test.errors && errors != nil { + t.Errorf("%s: got parse errors %v, want no parse errors", label, errors) + } if string(output) != test.want { t.Errorf("%s: got output %s, want %s", label, output, test.want) } diff --git a/visitor.go b/visitor.go index a1c2763..7fdd89d 100644 --- a/visitor.go +++ b/visitor.go @@ -260,6 +260,9 @@ func (w *walker) parseArray() bool { } w.onSeparator(',') w.scanNext() // consume comma + if w.scanner.Token() == CloseBracketToken && w.options.TrailingCommas { + break + } } else if needsComma { w.handleError(CommaExpected, nil, nil) }