Give the help examples that read no data and the exit codes, say a data path is no directory in one shape, suggest a record of one for a choice, name a JSON syntax error's line and column, and say no data is loaded from FakeStruct

This commit is contained in:
2026-10-11 23:27:33 +02:00
committed by Lillem4n
parent 1a7656d076
commit 9671600fff
5 changed files with 44 additions and 15 deletions
+15 -1
View File
@@ -4,7 +4,9 @@ package jsonvalue
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"unicode/utf8"
)
// Value is a JSON value that only Decode, String and Object make, so a template never compiles
@@ -15,7 +17,7 @@ type Value struct{ v any }
func Decode(b []byte) (Value, error) {
var v any
if !json.Valid(b) {
return Value{}, json.Unmarshal(b, &v)
return Value{}, located(b, json.Unmarshal(b, &v))
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.UseNumber()
@@ -23,6 +25,18 @@ func Decode(b []byte) (Value, error) {
return Value{v}, err
}
// located prefixes a syntax error with the line and column of the byte it stopped at.
func located(b []byte, err error) error {
var syntax *json.SyntaxError
if !errors.As(err, &syntax) {
return err
}
before := b[:max(syntax.Offset-1, 0)]
line := bytes.Count(before, []byte("\n")) + 1
column := utf8.RuneCount(before[bytes.LastIndexByte(before, '\n')+1:]) + 1
return fmt.Errorf("line %d, column %d: %w", line, column, err)
}
// String is the JSON string s.
func String(s string) Value { return Value{s} }