Skip to content

Commit 3435fee

Browse files
committed
Fixed handling of json decoding error #1423
1 parent ececd00 commit 3435fee

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

pkg/yqlib/encoder.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ func (o *orderedMap) UnmarshalJSON(data []byte) error {
4646
// cycle through k/v
4747
var tok json.Token
4848
for tok, err = dec.Token(); !errors.Is(err, io.EOF); tok, err = dec.Token() {
49+
if err != nil && !errors.Is(err, io.EOF) {
50+
return err
51+
}
52+
4953
// we can expect two types: string or Delim. Delim automatically means
5054
// that it is the closing bracket of the object, whereas string means
5155
// that there is another key.

pkg/yqlib/json_test.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,13 @@ var jsonScenarios = []formatScenario{
8484
input: `{"cat": "meow"}`,
8585
expected: "D0, P[], (!!map)::cat: meow\n",
8686
},
87+
{
88+
description: "bad json",
89+
skipDoc: true,
90+
input: `{"a": 1 "b": 2}`,
91+
expectedError: `bad file 'sample.yml': invalid character '"' after object key:value pair`,
92+
scenarioType: "decode-error",
93+
},
8794
{
8895
description: "Parse json: complex",
8996
subdescription: "JSON is a subset of yaml, so all you need to do is prettify the output",
@@ -303,7 +310,13 @@ func testJSONScenario(t *testing.T, s formatScenario) {
303310
test.AssertResultWithContext(t, s.expected, mustProcessFormatScenario(s, NewJSONDecoder(), NewJSONEncoder(0, false, false)), s.description)
304311
case "roundtrip-multi":
305312
test.AssertResultWithContext(t, s.expected, mustProcessFormatScenario(s, NewJSONDecoder(), NewJSONEncoder(2, false, false)), s.description)
306-
313+
case "decode-error":
314+
result, err := processFormatScenario(s, NewJSONDecoder(), NewJSONEncoder(2, false, false))
315+
if err == nil {
316+
t.Errorf("Expected error '%v' but it worked: %v", s.expectedError, result)
317+
} else {
318+
test.AssertResultComplexWithContext(t, s.expectedError, err.Error(), s.description)
319+
}
307320
default:
308321
panic(fmt.Sprintf("unhandled scenario type %q", s.scenarioType))
309322
}

0 commit comments

Comments
 (0)