Identify specific nodes in a JSON document (RFC 6901)
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Python implementation of JSON Pointer (RFC 6901) for identifying specific nodes within JSON documents. Provides both functional and object-oriented interfaces for resolving, setting, and manipulating JSON document elements through pointer expressions.
pip install jsonpointerimport jsonpointerCommon usage patterns:
from jsonpointer import resolve_pointer, set_pointer, JsonPointer, JsonPointerException
# For complete API access
from jsonpointer import (
resolve_pointer,
set_pointer,
JsonPointer,
JsonPointerException,
EndOfList,
escape,
unescape,
pairwise,
__author__,
__version__,
__website__,
__license__
)from jsonpointer import resolve_pointer, set_pointer, JsonPointer
# Sample JSON document
doc = {
"foo": {"bar": [1, 2, 3]},
"users": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
}
# Resolve pointers using functional interface
name = resolve_pointer(doc, "/users/0/name") # "Alice"
numbers = resolve_pointer(doc, "/foo/bar") # [1, 2, 3]
second_item = resolve_pointer(doc, "/foo/bar/1") # 2
# Set values using functional interface
updated_doc = set_pointer(doc, "/users/0/age", 31)
# Use object-oriented interface for advanced operations
pointer = JsonPointer("/users/0/name")
name = pointer.resolve(doc) # "Alice"
pointer.set(doc, "Alice Smith")
# Handle missing paths with defaults
result = resolve_pointer(doc, "/nonexistent/path", "default_value")
# Without default, raises JsonPointerException
try:
result = resolve_pointer(doc, "/nonexistent/path")
except JsonPointerException:
result = "path not found"High-level functions for common JSON pointer operations, providing simple access to resolve and modify JSON documents.
def resolve_pointer(doc, pointer, default=None):
"""
Resolves pointer against doc and returns the referenced object.
Args:
doc: JSON document to resolve against
pointer (str): JSON pointer string (e.g., "/foo/bar/0")
default: Default value to return if pointer cannot be resolved.
If not provided, raises JsonPointerException on missing paths.
Returns:
The referenced object or default value
Raises:
JsonPointerException: If pointer cannot be resolved and no default provided
"""
def set_pointer(doc, pointer, value, inplace=True):
"""
Resolves a pointer against doc and sets the value of the target within doc.
Args:
doc: JSON document to modify
pointer (str): JSON pointer string
value: Value to set at the pointer location
inplace (bool): Whether to modify document in place (default True)
Returns:
Modified document
Raises:
JsonPointerException: On invalid operations (e.g., setting root in place)
"""The JsonPointer class provides advanced functionality for complex pointer operations, including path manipulation, containment checking, and step-by-step resolution.
class JsonPointer:
"""A JSON Pointer that can reference parts of a JSON document"""
def __init__(self, pointer):
"""
Creates a JsonPointer from string representation.
Args:
pointer (str): JSON pointer string (must start with '/')
Raises:
JsonPointerException: If pointer format is invalid
"""
def resolve(self, doc, default=_nothing):
"""Resolves the pointer against doc and returns the referenced object"""
# Alias for resolve method
get = resolve
def set(self, doc, value, inplace=True):
"""Resolve the pointer against the doc and replace the target with value"""
@property
def path(self):
"""Returns the string representation of the pointer"""Helper functions for escaping and unescaping special characters in JSON pointer components, plus additional utilities.
def escape(s):
"""
Escapes special characters in JSON pointer parts.
Args:
s (str): String to escape
Returns:
str: Escaped string (~ becomes ~0, / becomes ~1)
"""
def unescape(s):
"""
Unescapes special characters in JSON pointer parts.
Args:
s (str): String to unescape
Returns:
str: Unescaped string (~1 becomes /, ~0 becomes ~)
"""
def pairwise(iterable):
"""
Transforms a list to a list of tuples of adjacent items.
Args:
iterable: Input iterable
Returns:
zip object yielding adjacent pairs: (s0,s1), (s1,s2), (s2,s3), ...
Empty iterator if input has less than 2 items.
Note:
Utility function that may be useful for pointer path manipulation
"""class JsonPointerException(Exception):
"""Exception raised for JSON pointer related errors"""
class EndOfList:
"""
Result of accessing element "-" of a list.
Represents the position after the last element.
Used for array append operations.
"""
def __init__(self, list_):
"""
Args:
list_: The list this EndOfList refers to
"""
list_
"""
The list that this EndOfList object refers to.
Type: list or sequence
Description: Reference to the original list/array
"""The package includes a command-line utility for resolving JSON pointers on JSON files.
# Resolve pointer on a JSON file
jsonpointer "/users/0/name" data.json
# Use pointer from file
jsonpointer -f pointer.txt data.json
# Pretty print output with indentation
jsonpointer "/users" data.json --indent 2JSON Pointers follow RFC 6901 syntax:
"" (empty string) - references the entire document"/property" - references doc["property"]"/0" (by index) - references doc[0]"/-" (append position) - references position after last element"/object/property/0" - references doc["object"]["property"][0]~ must be escaped as ~0/ must be escaped as ~1Examples:
"" → entire document (root)"/foo" → doc["foo"]"/foo/bar" → doc["foo"]["bar"]"/foo/0" → doc["foo"][0]"/foo/-" → end of doc["foo"] array (returns EndOfList object)"/a~1b" → doc["a/b"] (escaped slash)"/m~0n" → doc["m~n"] (escaped tilde)Important: The root pointer is an empty string "", not "/". The pointer "/" references a property with an empty string key.
Common exceptions and their causes:
__getitem__)Use the default parameter in resolve_pointer() to handle missing paths gracefully:
# Returns None instead of raising exception
value = resolve_pointer(doc, "/missing/path", None)
# Returns empty dict as fallback
config = resolve_pointer(doc, "/config", {})Package metadata available as module-level attributes:
__author__ # 'Stefan Kögl <stefan@skoegl.net>'
__version__ # '3.0.0'
__website__ # 'https://github.com/stefankoegl/python-json-pointer'
__license__ # 'Modified BSD License'