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")
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.
Index ¶
- 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 IsArrayEnd[T any](ref ArrayReference[T]) bool
- 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 any) error
- func ValidatePath(path any) error
- type ArrayReference
- type ObjectReference
- type Path
- type Reference
Constants ¶
This section is empty.
Variables ¶
var ErrFieldNotFound = errors.New("struct field not found")
ErrFieldNotFound is returned when trying to access a non-existent struct field.
var ErrIndexOutOfBounds = errors.New("array index out of bounds")
ErrIndexOutOfBounds is returned when array index is out of bounds.
var ErrInvalidIndex = errors.New("invalid array index")
ErrInvalidIndex is returned when an invalid array index is encountered. TypeScript original code from find.ts: throw new Error('INVALID_INDEX');
var ErrInvalidPath = errors.New("invalid path")
ErrInvalidPath is returned when a path is not an array. TypeScript original code from validate.ts: if (!isArray(path)) throw new Error('Invalid path.');
var ErrInvalidPathStep = errors.New("invalid path step")
ErrInvalidPathStep is returned when a path step is not string or number. TypeScript original code from validate.ts: throw new Error('Invalid path step.');
var ErrKeyNotFound = errors.New("map key not found")
ErrKeyNotFound is returned when trying to access a non-existent map key.
var ErrNilPointer = errors.New("cannot traverse through nil pointer")
ErrNilPointer is returned when trying to access through nil pointer.
var ErrNoParent = errors.New("no parent")
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');
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a path cannot be traversed. TypeScript original code from find.ts: throw new Error('NOT_FOUND');
var ErrPathTooLong = errors.New("path too long")
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.');
var ErrPointerInvalid = errors.New("pointer invalid")
ErrPointerInvalid is returned when a JSON Pointer string is invalid. TypeScript original code from validate.ts: if (pointer[0] !== '/') throw new Error('POINTER_INVALID');
var ErrPointerTooLong = errors.New("pointer too long")
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');
Functions ¶
func Get ¶
Get retrieves a value from document using string path components. Returns errors for invalid operations, similar to Find function.
func GetByPointer ¶ added in v0.3.0
GetByPointer retrieves a value from document using JSON Pointer string. Returns errors for invalid operations.
func IsArrayEnd ¶
func IsArrayEnd[T any](ref ArrayReference[T]) bool
IsArrayEnd checks if an array reference points to the end of the array. TypeScript original code: export const isArrayEnd = (ref: ArrayReference): boolean => ref.obj.length === ref.key;
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 ToPath ¶
ToPath converts a pointer (string or Path) to Path. If the input is a string, it parses it as JSON pointer. If the input is already a Path, it returns it as-is.
TypeScript Original: export const toPath = (pointer: string | Path) => (typeof pointer === 'string' ? parseJsonPointer(pointer) : pointer);