Documentation
¶
Overview ¶
Package jsonptr implements JSON Pointer (RFC 6901). Fast, with strong testsuite.
A JSON Pointer designates a value in a JSON document. Get, Set and Delete apply one, in its text form, to a document. Parse builds a Pointer, the parsed form, which can be moved around the document tree (Pointer.Property, Pointer.Index, Pointer.Up) before being applied with Pointer.In, Pointer.Set or Pointer.Delete.
A document is a tree of []any, map[string]any and terminal values, as produced by json.Unmarshal. Any part of it may also be left undecoded, as a json.RawMessage, a JSONDecoder or a partially deserialized container ([]json.RawMessage, map[string]json.RawMessage): those are traversed transparently and decoded only as far as needed.
Errors tell which part of the pointer evaluation failed, and why: see BadPointerError, PtrError and DocumentError.
Specification: https://tools.ietf.org/html/rfc6901
Example ¶
Example from https://tools.ietf.org/html/rfc6901#section-5
package main
import (
"encoding/json"
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
const JSON = `
{
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}`
var doc interface{}
_ = json.Unmarshal([]byte(JSON), &doc)
for _, ptr := range []string{
"/foo",
"/foo/0",
"/",
"/a~1b",
"/c%d",
"/e^f",
"/g|h",
"/i\\j",
"/k\"l",
"/ ",
"/m~0n",
} {
result, _ := jsonptr.Get(doc, ptr)
fmt.Printf("%-12q %#v\n", ptr, result)
}
}
Output: "/foo" []interface {}{"bar", "baz"} "/foo/0" "bar" "/" 0 "/a~1b" 1 "/c%d" 2 "/e^f" 3 "/g|h" 4 "/i\\j" 5 "/k\"l" 6 "/ " 7 "/m~0n" 8
Index ¶
- Variables
- func AppendEscape(dst []byte, name string) []byte
- func Delete(pdoc *interface{}, ptr string) (interface{}, error)
- func EscapeString(name string) string
- func Get(doc interface{}, ptr string) (interface{}, error)
- func MustValue(v interface{}, err error) interface{}
- func Set(pdoc *interface{}, ptr string, value interface{}) error
- func Unescape(b []byte) ([]byte, error)
- func UnescapeString(token string) (string, error)
- type BadPointerError
- type DocumentError
- type JSONDecoder
- type Pointer
- func (ptr Pointer) Copy() Pointer
- func (ptr Pointer) Delete(pdoc *interface{}) (interface{}, error)
- func (ptr *Pointer) Grow(n int)
- func (ptr Pointer) In(doc interface{}) (interface{}, error)
- func (ptr *Pointer) Index(index int) *Pointer
- func (ptr Pointer) IsRoot() bool
- func (ptr Pointer) LeafIndex() (int, error)
- func (ptr Pointer) LeafName() string
- func (ptr Pointer) MarshalText() (text []byte, err error)
- func (ptr *Pointer) Pop() string
- func (ptr *Pointer) Property(name string) *Pointer
- func (ptr Pointer) Set(pdoc *interface{}, value interface{}) error
- func (ptr Pointer) String() string
- func (ptr *Pointer) UnmarshalText(text []byte) error
- func (ptr *Pointer) Up() *Pointer
- type PtrError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrSyntax = errors.New("invalid JSON pointer") ErrIndex = errors.New("invalid array index") ErrProperty = errors.New("property not found") ErrRoot = errors.New("can't go up from root") ErrDeleteRoot = errors.New("can't delete root") ErrUsage = errors.New("invalid use of jsonptr.UnescapeString on string with '/'") )
Functions ¶
func AppendEscape ¶
AppendEscape appends the escaped name to dst and returns it. The buffer grows (and so is reallocated) if necessary.
func Delete ¶
Delete removes the value at the location pointed by ptr in the document *pdoc, and returns it. An array element is removed by shifting the remaining ones.
*pdoc may be any document accepted by Get. The root of the document can't be deleted (ErrDeleteRoot). The value must exist (ErrProperty, ErrIndex); index "-" is not accepted.
The returned value is the one stored in the tree, so it is a json.RawMessage when the container of the value is a map[string]json.RawMessage or a []json.RawMessage (including when it results from the lazy decoding below).
Every container on the path to the value, except the container of the value itself, is rewritten in the tree as a map[string]any or a []any. A json.RawMessage or JSONDecoder on the path is decoded lazily, so only the containers on the path are decoded and the values outside the path are kept raw. A map[string]json.RawMessage or a []json.RawMessage on the path is converted, its members are kept raw.
In case of error the document is left unchanged, except that a JSONDecoder on the path is replaced by the raw value read from it.
func EscapeString ¶
EscapeString escapes a property name with JSON Pointer escapes:
'~' => `~0` '/' => `~1`
Example ¶
package main
import (
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
fmt.Println(jsonptr.EscapeString("a~b c/d"))
}
Output: a~0b c~1d
func Get ¶
Get extracts a value from a JSON-like data tree.
In the common case doc is a deserialized document, made of []any, map[string]any and terminal values. The value designated by ptr is then returned as it is stored in doc: a container is the very one held by the tree, so modifying it modifies doc.
In case of error a *BadPointerError (invalid pointer), a *PtrError (the pointer doesn't match the document) or a *DocumentError (the document can't be traversed or decoded) is returned.
Undecoded values ¶
doc, or any value nested in it, may also be:
- a encoding/json.RawMessage
- a JSONDecoder (such as *encoding/json.Decoder) for streamed decoding
- a partially deserialized container: []json.RawMessage or map[string]json.RawMessage
Those may be mixed with the deserialized containers at any level of the tree and are traversed transparently.
However, when such an undecoded value is the one designated by ptr, it is deserialized, deeply: the result is a copy, made of []any, map[string]any and terminal values, so modifying it does not modify doc. The original values are lost in the process: JSON numbers become float64, and a JSONDecoder is consumed.
Members of a deserialized container are never decoded, so a json.RawMessage nested in the returned value is returned as is.
func MustValue ¶
func MustValue(v interface{}, err error) interface{}
MustValue allows to wrap a call to some jsonptr function which returns a value to transform any error into a panic.
func Set ¶
Set stores value at the location pointed by ptr in the document *pdoc.
*pdoc may be any document accepted by Get. The root of the document (ptr == "") may be replaced. Otherwise the parent of the location must exist: only the leaf is created if it doesn't exist. In an array, index "-" appends the value, and an index beyond the end extends the array with nulls.
value is stored as-is, except a JSONDecoder which is drained of its next value into a json.RawMessage.
Every container on the path to the value is rewritten in the tree as a map[string]any or a []any. A json.RawMessage or JSONDecoder on the path is decoded lazily, so only the containers on the path are decoded and the values outside the path are kept raw. A map[string]json.RawMessage or a []json.RawMessage on the path is converted, its members are kept raw.
In case of error the document is left unchanged, except that a JSONDecoder on the path is replaced by the raw value read from it (a JSONDecoder given as value may also have been read).
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
newArray := []interface{}(nil)
newObject := map[string]interface{}(nil)
var doc interface{}
for _, step := range []struct {
where string
what interface{}
}{
{"", newObject},
{"/arr", newArray},
{"/arr/-", 3},
{"/arr/-", 2},
{"/arr/-", 1},
{"/obj", newObject},
{"/obj/str", "hello"},
{"/obj/bool", true},
{"/arr/-", 0},
{"/obj/", nil},
} {
err := jsonptr.Set(&doc, step.where, step.what)
if err != nil {
panic(err)
}
//fmt.Printf("%#v\n", doc)
}
fmt.Println(func() string { x, _ := json.Marshal(doc); return string(x) }())
}
Output: {"arr":[3,2,1,0],"obj":{"":null,"bool":true,"str":"hello"}}
func Unescape ¶
Unescape unescapes a property name in place:
`~1` => '/' `~0` => '~'
Any '~' followed by something else (or nothing) is an error ErrSyntax. If the input contains '/' the result is undefined (may panic).
func UnescapeString ¶
UnescapeString unescapes a property name:
`~1` => '/' `~0` => '~'
Any '~' followed by something else (or nothing) is an error ErrSyntax. If the input contains '/' the result is undefined (may panic).
Example ¶
package main
import (
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
s, _ := jsonptr.UnescapeString("a~0b c~1d")
fmt.Println(s)
}
Output: a~b c/d
Example (Error) ¶
package main
import (
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
_, err := jsonptr.UnescapeString("a~x")
fmt.Println("jsonptr.ErrSyntax?", err == jsonptr.ErrSyntax)
fmt.Println(err)
}
Output: jsonptr.ErrSyntax? true invalid JSON pointer
Types ¶
type BadPointerError ¶
type BadPointerError struct {
// Ptr is the substring of the original pointer where the error occurred
BadPtr string
// Err is [ErrSyntax]
Err error
}
BadPointerError signals JSON Pointer parsing errors
func (*BadPointerError) Error ¶
func (e *BadPointerError) Error() string
Error implements the 'error' interface
func (*BadPointerError) Unwrap ¶
func (e *BadPointerError) Unwrap() error
Unwrap allows to unwrap the error (see errors.Unwrap).
type DocumentError ¶
type DocumentError struct {
// Ptr is the substring of the original pointer where the error occurred.
// It is empty when the location is not known or not relevant (JSON syntax
// errors for example).
Ptr string
Err error
}
DocumentError signals a document that can't be processed by this library
func (*DocumentError) Error ¶
func (e *DocumentError) Error() string
Error implements the 'error' interface.
func (*DocumentError) Unwrap ¶
func (e *DocumentError) Unwrap() error
Unwrap allows to unwrap the error (see errors.Unwrap).
type JSONDecoder ¶
JSONDecoder is a subset of the interface of encoding/json.Decoder.
It may be given to Get, Pointer.In, Set or Delete for streamed decoding, either as the document itself or as any value nested in it. Set also accepts it as the value to store.
A JSONDecoder is consumed by those calls, so it can't be reused: Get and Pointer.In read from it up to the designated value, while Set and Delete read its next value as a json.RawMessage and store that raw value in the document in place of the decoder.
Example ¶
ExampleJSONDecoder shows how to extract from a streamed JSON document.
package main
import (
"encoding/json"
"fmt"
"strings"
"testing/iotest"
"github.com/dolmen-go/jsonptr"
)
func main() {
stream := iotest.OneByteReader(strings.NewReader(`{"a": 42,"b":5}`))
decoder := json.NewDecoder(stream)
result, _ := jsonptr.Get(decoder, "/a")
fmt.Println(result)
}
Output: 42
type Pointer ¶
type Pointer []string
Pointer represents a mutable parsed JSON Pointer.
The Go representation is a array of non-encoded path elements. This allows to use type conversion from/to a []string.
Example (Conversion) ¶
package main
import (
"fmt"
"github.com/dolmen-go/jsonptr"
)
func main() {
fmt.Printf("%q\n\n", jsonptr.Pointer{"foo", "bar", "a/b", "x~y"})
for _, ptr := range []jsonptr.Pointer{
nil,
{},
{"a", "b"},
{"a~/b"},
} {
fmt.Printf("%q\n", ptr.String())
}
}
Output: "/foo/bar/a~1b/x~0y" "" "" "/a/b" "/a~0~1b"
func (Pointer) Delete ¶
Delete removes the value at the location pointed by ptr in the document *pdoc, and returns it. An array element is removed by shifting the remaining ones. The root of the document can't be deleted (ErrDeleteRoot).
See Delete for the value returned, the handling of the documents which are not fully deserialized, and the errors reported.
func (*Pointer) Grow ¶
Grow allows to prepare space for growth (before use of Pointer.Property/Pointer.Index).
func (Pointer) In ¶
In returns the value from doc pointed by ptr.
doc may be any document accepted by Get.
func (*Pointer) Index ¶
Index moves the pointer deeper, following an array index. The pointer is returned for chaining.
func (Pointer) LeafIndex ¶
LeafIndex returns the last part of the pointer as an array index. -1 is returned for "-".
func (Pointer) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Pointer) Pop ¶
Pop removes the last element of the pointer and returns it.
Panics if already at root.
func (*Pointer) Property ¶
Property moves the pointer deeper, following a property name. The pointer is returned for chaining.
func (Pointer) Set ¶
Set stores value at the location pointed by ptr in the document *pdoc. A root pointer replaces the whole document. Otherwise the parent of the location must exist: only the leaf is created if it doesn't exist. In an array, index "-" appends the value, and an index beyond the end extends the array with nulls.
See Set for how value is stored, the handling of the documents which are not fully deserialized, and the errors reported.
func (Pointer) String ¶
String returns a JSON Pointer string, escaping components when necessary: '~' is replaced by "~0", '/' by "~1"
func (*Pointer) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type PtrError ¶
type PtrError struct {
// Ptr is the substring of the original pointer where the error occurred.
Ptr string
// Err is one of [ErrIndex], [ErrProperty].
Err error
}
PtrError signals JSON Pointer navigation errors.
func (*PtrError) Unwrap ¶
Unwrap allows to unwrap the error (see errors.Unwrap).