Skip to content

Commit 596a8c3

Browse files
haoqixumvdan
authored andcommitted
encoding/json: fix location for JSON syntax error
The JSON decoder utilizes `parser.ParseExpr` to parse input data, which could be a valid CUE expression but an invalid JSON. Using the error position returned by `parser.ParseExpr` as output may cause cue to either omit the position or report the wrong position This change uses the offset returned by the JSON parser and recalculate the position to ensure the reported position is accurate. Fixes #3317 Change-Id: I019ab80c275d658f5773501d766ee9d03261ab58 Signed-off-by: haoqixu <[email protected]> Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199094 Reviewed-by: Daniel Martí <[email protected]> TryBot-Result: CUEcueckoo <[email protected]>
1 parent 677ece8 commit 596a8c3

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
! exec cue export x1.json
2+
stderr 'x1*.json:4:3'
3+
4+
! exec cue export x2.json
5+
stderr 'x2.json:1:6'
6+
7+
! exec cue export x3.json
8+
stderr 'x3.json:1:1'
9+
10+
! exec cue export x4.json
11+
stderr 'x4.json:1:1'
12+
13+
-- x1.json --
14+
{
15+
"foo": true,
16+
"bar": 2
17+
"baz": false
18+
}
19+
20+
-- x2.json --
21+
"baz": false
22+
23+
-- x3.json --
24+
baz: false
25+
26+
-- x4.json --

encoding/json/json.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,16 @@ func extract(path string, b []byte) (ast.Expr, error) {
8787
}
8888
var x interface{}
8989
err := json.Unmarshal(b, &x)
90+
91+
if len(b) > 0 {
92+
var synErr *json.SyntaxError
93+
if errors.As(err, &synErr) {
94+
tokFile := token.NewFile(path, 0, len(b))
95+
tokFile.SetLinesForContent(b)
96+
p = tokFile.Pos(int(synErr.Offset-1), token.NoRelPos)
97+
}
98+
}
99+
90100
return nil, errors.Wrapf(err, p, "invalid JSON for file %q", path)
91101
}
92102
return expr, nil

0 commit comments

Comments
 (0)