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.ParseJsonPointer("/users/0/name")
// Find value with error handling
ref, err := jsonpointer.Find(data, path)
if err != nil {
// Handle error
}
// Get value without errors (returns nil for not found)
value := jsonpointer.Get(data, path)
// Validate JSON Pointer
err = jsonpointer.ValidateJsonPointer("/users/0/name")
Breaking Change Notice: This version is a complete rewrite using modern Go generics with zero backward compatibility. All function signatures use 'any' instead of 'interface{}' and follow TypeScript API exactly.
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 EscapeComponent(component string) string
- func FormatJsonPointer(path Path) string
- func Get(val any, path Path) any
- 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 any) bool
- func UnescapeComponent(component string) string
- func ValidateJsonPointer(pointer any) error
- func ValidatePath(path any) error
- type ArrayReference
- type ObjectReference
- type Path
- type PathStep
- type Reference
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidIndex = errors.New("invalid 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 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 EscapeComponent ¶
EscapeComponent escapes a JSON pointer path component. Returns the escaped component string.
TypeScript Original:
export function escapeComponent(component: string): string {
if (component.indexOf('/') === -1 && component.indexOf('~') === -1) return component;
return component.replace(r3, '~0').replace(r4, '~1');
}
func FormatJsonPointer ¶
FormatJsonPointer escapes and formats a path slice like []any{"foo", "bar"} to JSON pointer like "/foo/bar".
TypeScript Original:
export function formatJsonPointer(path: Path): string {
if (isRoot(path)) return '';
return '/' + path.map((component) => escapeComponent(String(component))).join('/');
}
func Get ¶
Get retrieves a value from object using path (never returns errors, returns nil for not found).
func IsArrayEnd ¶
func IsArrayEnd[T any](ref ArrayReference[T]) bool
IsArrayEnd checks if an array reference points to the end of the array.
func IsArrayReference ¶
IsArrayReference checks if a Reference points to an array element.
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.
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;
}
func UnescapeComponent ¶
UnescapeComponent un-escapes a JSON pointer path component. Returns the unescaped component string.
TypeScript Original:
export function unescapeComponent(component: string): string {
if (component.indexOf('~') === -1) return component;
return component.replace(r1, '/').replace(r2, '~');
}
func ValidateJsonPointer ¶
ValidateJsonPointer validates a JSON Pointer string or Path.
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"` }
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 []PathStep
Path represents a JSON Pointer path as array of steps. TypeScript original code: export type Path = readonly PathStep[];
func Parent ¶
Parent returns parent path, e.g. for []any{"foo", "bar", "baz"} returns []any{"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 ParseJsonPointer ¶
ParseJsonPointer converts JSON pointer like "/foo/bar" to path slice like []any{"foo", "bar"}, while also un-escaping reserved characters and precomputing array indices for performance.
TypeScript Original:
export function parseJsonPointer(pointer: string): Path {
if (!pointer) return [];
// TODO: Performance of this line can be improved: (1) don't use .split(); (2) don't use .map().
return pointer.slice(1).split('/').map(unescapeComponent);
}
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);
type PathStep ¶
type PathStep = any
PathStep represents a single step in a JSON Pointer path (string or number). TypeScript original code: export type PathStep = string | number;
type Reference ¶
type Reference struct {
Val any `json:"val"`
Obj any `json:"obj,omitempty"`
Key any `json:"key,omitempty"`
}
Reference represents a found reference with context. TypeScript original code:
export interface Reference {
readonly val: unknown;
readonly obj?: unknown | object | unknown[];
readonly key?: string | number;
}