Debian Codegraph @

internal/util/json_pointer.go

raw
1 // Copyright (c) 2020, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package util
8
9 import (
10 "strconv"
11 "strings"
12 )
13
14 var jsonPointerEsc = strings.NewReplacer("~0", "~", "~1", "/")
15
16 const (
17 ErrJSONPointerInvalid = "invalid JSON pointer"
18 ErrJSONPointerKeyNotFound = "key not found"
19 ErrJSONPointerArrayNoIndex = "array but not an index in JSON pointer"
20 ErrJSONPointerArrayOutOfRange = "out of array range"
21 ErrJSONPointerArrayBadType = "not a map nor an array"
22 )
23
24 type JSONPointerError struct {
25 Type string
26 Pointer string
27 }
28
29 func (e *JSONPointerError) Error() string {
30 if e.Pointer == "" {
31 return e.Type
32 }
33 return e.Type + " @" + e.Pointer
34 }
35
36 // JSONPointer returns the value corresponding to JSON pointer
37 // pointer in v as [RFC 6901] specifies it. To be searched, v has
38 // to contains map[string]any or []any values. All
39 // other types fail to be searched.
40 //
41 // [RFC 6901]: https://tools.ietf.org/html/rfc6901
42 func JSONPointer(v any, pointer string) (any, error) {
43 if !strings.HasPrefix(pointer, "/") {
44 if pointer == "" {
45 return v, nil
46 }
47 return nil, &JSONPointerError{Type: ErrJSONPointerInvalid}
48 }
49
50 pos := 0
51 for _, part := range strings.Split(pointer[1:], "/") {
52 pos += 1 + len(part)
53 part = jsonPointerEsc.Replace(part)
54
55 switch tv := v.(type) {
56 case map[string]any:
57 var ok bool
58 v, ok = tv[part]
59 if !ok {
60 return nil, &JSONPointerError{
61 Type: ErrJSONPointerKeyNotFound,
62 Pointer: pointer[:pos],
63 }
64 }
65
66 case []any:
67 i, err := strconv.Atoi(part)
68 if err != nil || i < 0 {
69 return nil, &JSONPointerError{
70 Type: ErrJSONPointerArrayNoIndex,
71 Pointer: pointer[:pos],
72 }
73 }
74 if i >= len(tv) {
75 return nil, &JSONPointerError{
76 Type: ErrJSONPointerArrayOutOfRange,
77 Pointer: pointer[:pos],
78 }
79 }
80 v = tv[i]
81
82 default:
83 return nil, &JSONPointerError{
84 Type: ErrJSONPointerArrayBadType,
85 Pointer: pointer[:pos],
86 }
87 }
88 }
89
90 return v, nil
91 }