Documentation
¶
Overview ¶
Package jsonpointer provides JSON Pointer (RFC 6901) implementation for Go. This is a direct port of the TypeScript json-pointer library with identical behavior, using modern Go generics for type safety and performance.
This package implements helper functions for JSON Pointer (RFC 6901) specification. https://tools.ietf.org/html/rfc6901
TypeScript original source: https://github.com/jsonjoy-com/json-pointer
Usage:
import "github.com/kaptinlin/jsonpointer"
// Parse JSON Pointer string to path
path := jsonpointer.Parse("/users/0/name")
// Find value with error handling
ref, err := jsonpointer.Find(data, path...)
if err != nil {
// Handle error
}
// Get value with error handling
value, err := jsonpointer.Get(data, path...)
if err != nil {
// Handle error
}
// Validate JSON Pointer
err = jsonpointer.Validate("/users/0/name")
Public traversal APIs return errors for invalid paths and unsupported access patterns. This package does not expose Must* wrappers and does not use panic for traversal failures.
Index ¶
- Constants
- Variables
- func Escape(component string) string
- func Format(path ...string) string
- func Get(doc any, path ...string) (any, error)
- func GetByPointer(doc any, pointer string) (any, error)
- func IsArrayReference(ref Reference) bool
- func IsChild(parent, child Path) bool
- func IsInteger(str string) bool
- func IsObjectReference(ref Reference) bool
- func IsPathEqual(p1, p2 Path) bool
- func IsRoot(path Path) bool
- func IsValidIndex(index string) bool
- func Unescape(component string) string
- func Validate(pointer string) error
- func ValidatePath(path Path) error
- type ArrayReference
- type ObjectReference
- type Path
- type Reference
Examples ¶
Constants ¶
const ( // MaxPointerLength is the maximum allowed length for JSON Pointer strings. // Aligned with TypeScript: > 1024 is invalid MaxPointerLength = 1024 // MaxPathLength is the maximum allowed length for Path arrays. // Aligned with TypeScript: > 256 is invalid MaxPathLength = 256 )
Validation limits aligned with TypeScript implementation
Variables ¶
var ( // ErrInvalidIndex is returned when an invalid array index is encountered. // TypeScript original code from find.ts: // throw new Error('INVALID_INDEX'); ErrInvalidIndex = errors.New("invalid array index") // ErrNotFound is returned when a path cannot be traversed. // TypeScript original code from find.ts: // throw new Error('NOT_FOUND'); ErrNotFound = errors.New("not found") // ErrNoParent is returned when trying to get parent of root path. // TypeScript original code from util.ts: // if (path.length < 1) throw new Error('NO_PARENT'); ErrNoParent = errors.New("no parent") // ErrPointerInvalid is returned when a JSON Pointer string is invalid. // TypeScript original code from validate.ts: // if (pointer[0] !== '/') throw new Error('POINTER_INVALID'); ErrPointerInvalid = errors.New("pointer invalid") // ErrPointerTooLong is returned when a JSON Pointer string exceeds maximum length. // TypeScript original code from validate.ts: // if (pointer.length > 1024) throw new Error('POINTER_TOO_LONG'); ErrPointerTooLong = errors.New("pointer too long") // ErrInvalidPath is returned when a path is not an array. // TypeScript original code from validate.ts: // if (!isArray(path)) throw new Error('Invalid path.'); ErrInvalidPath = errors.New("invalid path") // ErrPathTooLong is returned when a path array exceeds maximum length. // TypeScript original code from validate.ts: // if (path.length > 256) throw new Error('Path too long.'); ErrPathTooLong = errors.New("path too long") // ErrInvalidPathStep is returned when a path step is not string or number. // TypeScript original code from validate.ts: // throw new Error('Invalid path step.'); ErrInvalidPathStep = errors.New("invalid path step") )
Predefined errors matching TypeScript error semantics.
var ( // ErrIndexOutOfBounds is returned when array index is out of bounds. ErrIndexOutOfBounds = errors.New("array index out of bounds") // ErrNilPointer is returned when trying to access through nil pointer. ErrNilPointer = errors.New("cannot traverse through nil pointer") // ErrFieldNotFound is returned when trying to access a non-existent struct field. ErrFieldNotFound = errors.New("struct field not found") // ErrKeyNotFound is returned when trying to access a non-existent map key. ErrKeyNotFound = errors.New("map key not found") )
Go-specific errors providing more detailed information for Go use cases.
Functions ¶
func Get ¶
Get retrieves a value from document using string path components. Returns errors for invalid operations, similar to Find function.
Example ¶
package main
import (
"fmt"
"log"
"github.com/kaptinlin/jsonpointer"
)
func main() {
doc := map[string]any{
"users": []any{
map[string]any{"name": "Alice"},
},
}
name, err := jsonpointer.Get(doc, "users", "0", "name")
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
}
Output: Alice
Example (Struct) ¶
package main
import (
"fmt"
"log"
"github.com/kaptinlin/jsonpointer"
)
func main() {
type user struct {
Name string `json:"name"`
Email string `json:"email"`
}
val, err := jsonpointer.Get(&user{Name: "Alice", Email: "alice@example.com"}, "email")
if err != nil {
log.Fatal(err)
}
fmt.Println(val)
}
Output: alice@example.com
func GetByPointer ¶ added in v0.3.0
GetByPointer retrieves a value from document using JSON Pointer string. Returns errors for invalid operations.
func IsArrayReference ¶
IsArrayReference checks if a Reference points to an array element. TypeScript original code: export const isArrayReference = <T = unknown>(ref: Reference): ref is ArrayReference<T> =>
isArray(ref.obj) && typeof ref.key === 'number';
func IsChild ¶
IsChild returns true if parent contains child path, false otherwise.
TypeScript Original:
export function isChild(parent: Path, child: Path): boolean {
if (parent.length >= child.length) return false;
for (let i = 0; i < parent.length; i++) if (parent[i] !== child[i]) return false;
return true;
}
func IsInteger ¶
IsInteger checks if a string contains only digit characters (0-9).
TypeScript Original:
export const isInteger = (str: string): boolean => {
const len = str.length;
let i = 0;
let charCode: any;
while (i < len) {
charCode = str.charCodeAt(i);
if (charCode >= 48 && charCode <= 57) {
i++;
continue;
}
return false;
}
return true;
};
func IsObjectReference ¶
IsObjectReference checks if a Reference points to an object property. TypeScript original code: export const isObjectReference = <T = unknown>(ref: Reference): ref is ObjectReference<T> =>
typeof ref.obj === 'object' && typeof ref.key === 'string';
func IsPathEqual ¶
IsPathEqual returns true if two paths are equal, false otherwise.
TypeScript Original:
export function isPathEqual(p1: Path, p2: Path): boolean {
if (p1.length !== p2.length) return false;
for (let i = 0; i < p1.length; i++) if (p1[i] !== p2[i]) return false;
return true;
}
func IsRoot ¶
IsRoot returns true if JSON Pointer points to root value, false otherwise.
TypeScript Original: export const isRoot = (path: Path): boolean => !path.length;
func IsValidIndex ¶
IsValidIndex checks if path component can be a valid array index.
TypeScript Original:
export function isValidIndex(index: string | number): boolean {
if (typeof index === 'number') return true;
const n = Number.parseInt(index, 10);
return String(n) === index && n >= 0;
}
Types ¶
type ArrayReference ¶
type ArrayReference[T any] struct { // Use pointer for undefined | T semantics (nil = undefined) Val *T `json:"val"` Obj []T `json:"obj"` Key int `json:"key"` // Numeric index for array access }
ArrayReference represents a reference to an array element. TypeScript original code:
export interface ArrayReference<T = unknown> {
readonly val: undefined | T;
readonly obj: T[];
readonly key: number;
}
type ObjectReference ¶
type ObjectReference[T any] struct { Val T `json:"val"` Obj map[string]T `json:"obj"` Key string `json:"key"` }
ObjectReference represents a reference to an object property. TypeScript original code:
export interface ObjectReference<T = unknown> {
readonly val: T;
readonly obj: Record<string, T>;
readonly key: string;
}
type Path ¶
type Path []string
Path represents a JSON Pointer path as array of string tokens.
func Parent ¶
Parent returns parent path, e.g. for []string{"foo", "bar", "baz"} returns []string{"foo", "bar"}. Returns ErrNoParent if the path has no parent (empty or root path).
TypeScript Original:
export function parent(path: Path): Path {
if (path.length < 1) throw new Error('NO_PARENT');
return path.slice(0, path.length - 1);
}
func Parse ¶ added in v0.3.0
Parse parses a JSON Pointer string to a path array.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/jsonpointer"
)
func main() {
path := jsonpointer.Parse("/foo~1bar/tilde~0key")
fmt.Println(path)
fmt.Println(jsonpointer.Format(path...))
}
Output: [foo/bar tilde~key] /foo~1bar/tilde~0key
type Reference ¶
type Reference struct {
Val any `json:"val"`
Obj any `json:"obj,omitempty"`
Key string `json:"key,omitempty"`
}
Reference represents a found reference with context.
func Find ¶
Find locates a reference in document using string path components. Returns errors for invalid operations.
func FindByPointer ¶
FindByPointer locates a reference in document using JSON Pointer string.
Example ¶
package main
import (
"fmt"
"log"
"github.com/kaptinlin/jsonpointer"
)
func main() {
doc := map[string]any{
"foo/bar": map[string]any{
"tilde~key": "ready",
},
}
ref, err := jsonpointer.FindByPointer(doc, "/foo~1bar/tilde~0key")
if err != nil {
log.Fatal(err)
}
fmt.Println(ref.Val)
fmt.Println(ref.Key)
}
Output: ready tilde~key