or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdjsonpointer-class.md

index.mddocs/

0

# jsonpointer

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: jsonpointer

7

- **Language**: Python

8

- **Installation**: `pip install jsonpointer`

9

- **Version**: 3.0.0

10

- **License**: Modified BSD License

11

- **RFC Compliance**: RFC 6901

12

13

## Core Imports

14

15

```python

16

import jsonpointer

17

```

18

19

Common usage patterns:

20

21

```python

22

from jsonpointer import resolve_pointer, set_pointer, JsonPointer, JsonPointerException

23

24

# For complete API access

25

from jsonpointer import (

26

resolve_pointer,

27

set_pointer,

28

JsonPointer,

29

JsonPointerException,

30

EndOfList,

31

escape,

32

unescape,

33

pairwise,

34

__author__,

35

__version__,

36

__website__,

37

__license__

38

)

39

```

40

41

## Basic Usage

42

43

```python

44

from jsonpointer import resolve_pointer, set_pointer, JsonPointer

45

46

# Sample JSON document

47

doc = {

48

"foo": {"bar": [1, 2, 3]},

49

"users": [

50

{"name": "Alice", "age": 30},

51

{"name": "Bob", "age": 25}

52

]

53

}

54

55

# Resolve pointers using functional interface

56

name = resolve_pointer(doc, "/users/0/name") # "Alice"

57

numbers = resolve_pointer(doc, "/foo/bar") # [1, 2, 3]

58

second_item = resolve_pointer(doc, "/foo/bar/1") # 2

59

60

# Set values using functional interface

61

updated_doc = set_pointer(doc, "/users/0/age", 31)

62

63

# Use object-oriented interface for advanced operations

64

pointer = JsonPointer("/users/0/name")

65

name = pointer.resolve(doc) # "Alice"

66

pointer.set(doc, "Alice Smith")

67

68

# Handle missing paths with defaults

69

result = resolve_pointer(doc, "/nonexistent/path", "default_value")

70

71

# Without default, raises JsonPointerException

72

try:

73

result = resolve_pointer(doc, "/nonexistent/path")

74

except JsonPointerException:

75

result = "path not found"

76

```

77

78

## Capabilities

79

80

### Functional Interface

81

82

High-level functions for common JSON pointer operations, providing simple access to resolve and modify JSON documents.

83

84

```python { .api }

85

def resolve_pointer(doc, pointer, default=None):

86

"""

87

Resolves pointer against doc and returns the referenced object.

88

89

Args:

90

doc: JSON document to resolve against

91

pointer (str): JSON pointer string (e.g., "/foo/bar/0")

92

default: Default value to return if pointer cannot be resolved.

93

If not provided, raises JsonPointerException on missing paths.

94

95

Returns:

96

The referenced object or default value

97

98

Raises:

99

JsonPointerException: If pointer cannot be resolved and no default provided

100

"""

101

102

def set_pointer(doc, pointer, value, inplace=True):

103

"""

104

Resolves a pointer against doc and sets the value of the target within doc.

105

106

Args:

107

doc: JSON document to modify

108

pointer (str): JSON pointer string

109

value: Value to set at the pointer location

110

inplace (bool): Whether to modify document in place (default True)

111

112

Returns:

113

Modified document

114

115

Raises:

116

JsonPointerException: On invalid operations (e.g., setting root in place)

117

"""

118

```

119

120

### Object-Oriented Interface

121

122

The JsonPointer class provides advanced functionality for complex pointer operations, including path manipulation, containment checking, and step-by-step resolution.

123

124

```python { .api }

125

class JsonPointer:

126

"""A JSON Pointer that can reference parts of a JSON document"""

127

128

def __init__(self, pointer):

129

"""

130

Creates a JsonPointer from string representation.

131

132

Args:

133

pointer (str): JSON pointer string (must start with '/')

134

135

Raises:

136

JsonPointerException: If pointer format is invalid

137

"""

138

139

def resolve(self, doc, default=_nothing):

140

"""Resolves the pointer against doc and returns the referenced object"""

141

142

# Alias for resolve method

143

get = resolve

144

145

def set(self, doc, value, inplace=True):

146

"""Resolve the pointer against the doc and replace the target with value"""

147

148

@property

149

def path(self):

150

"""Returns the string representation of the pointer"""

151

```

152

153

[JsonPointer Class](./jsonpointer-class.md)

154

155

### Utility Functions

156

157

Helper functions for escaping and unescaping special characters in JSON pointer components, plus additional utilities.

158

159

```python { .api }

160

def escape(s):

161

"""

162

Escapes special characters in JSON pointer parts.

163

164

Args:

165

s (str): String to escape

166

167

Returns:

168

str: Escaped string (~ becomes ~0, / becomes ~1)

169

"""

170

171

def unescape(s):

172

"""

173

Unescapes special characters in JSON pointer parts.

174

175

Args:

176

s (str): String to unescape

177

178

Returns:

179

str: Unescaped string (~1 becomes /, ~0 becomes ~)

180

"""

181

182

def pairwise(iterable):

183

"""

184

Transforms a list to a list of tuples of adjacent items.

185

186

Args:

187

iterable: Input iterable

188

189

Returns:

190

zip object yielding adjacent pairs: (s0,s1), (s1,s2), (s2,s3), ...

191

Empty iterator if input has less than 2 items.

192

193

Note:

194

Utility function that may be useful for pointer path manipulation

195

"""

196

```

197

198

### Exception Handling

199

200

```python { .api }

201

class JsonPointerException(Exception):

202

"""Exception raised for JSON pointer related errors"""

203

204

class EndOfList:

205

"""

206

Result of accessing element "-" of a list.

207

Represents the position after the last element.

208

Used for array append operations.

209

"""

210

211

def __init__(self, list_):

212

"""

213

Args:

214

list_: The list this EndOfList refers to

215

"""

216

217

list_

218

"""

219

The list that this EndOfList object refers to.

220

221

Type: list or sequence

222

Description: Reference to the original list/array

223

"""

224

```

225

226

## Command Line Interface

227

228

The package includes a command-line utility for resolving JSON pointers on JSON files.

229

230

```bash

231

# Resolve pointer on a JSON file

232

jsonpointer "/users/0/name" data.json

233

234

# Use pointer from file

235

jsonpointer -f pointer.txt data.json

236

237

# Pretty print output with indentation

238

jsonpointer "/users" data.json --indent 2

239

```

240

241

## JSON Pointer Syntax

242

243

JSON Pointers follow RFC 6901 syntax:

244

245

- **Root document**: `""` (empty string) - references the entire document

246

- **Object property**: `"/property"` - references `doc["property"]`

247

- **Array element**: `"/0"` (by index) - references `doc[0]`

248

- **End of array**: `"/-"` (append position) - references position after last element

249

- **Nested access**: `"/object/property/0"` - references `doc["object"]["property"][0]`

250

- **Special characters**:

251

- `~` must be escaped as `~0`

252

- `/` must be escaped as `~1`

253

254

Examples:

255

- `""` → entire document (root)

256

- `"/foo"``doc["foo"]`

257

- `"/foo/bar"``doc["foo"]["bar"]`

258

- `"/foo/0"``doc["foo"][0]`

259

- `"/foo/-"` → end of `doc["foo"]` array (returns EndOfList object)

260

- `"/a~1b"``doc["a/b"]` (escaped slash)

261

- `"/m~0n"``doc["m~n"]` (escaped tilde)

262

263

**Important**: The root pointer is an empty string `""`, not `"/"`. The pointer `"/"` references a property with an empty string key.

264

265

## Error Handling

266

267

Common exceptions and their causes:

268

269

- **JsonPointerException**: Invalid pointer format, missing properties, array index out of bounds

270

- **TypeError**: Document doesn't support indexing (not a dict, list, or object with `__getitem__`)

271

- **KeyError**: Property doesn't exist in object

272

- **IndexError**: Array index out of bounds

273

274

Use the `default` parameter in `resolve_pointer()` to handle missing paths gracefully:

275

276

```python

277

# Returns None instead of raising exception

278

value = resolve_pointer(doc, "/missing/path", None)

279

280

# Returns empty dict as fallback

281

config = resolve_pointer(doc, "/config", {})

282

```

283

284

## Module Metadata

285

286

Package metadata available as module-level attributes:

287

288

```python { .api }

289

__author__ # 'Stefan Kögl <stefan@skoegl.net>'

290

__version__ # '3.0.0'

291

__website__ # 'https://github.com/stefankoegl/python-json-pointer'

292

__license__ # 'Modified BSD License'

293

```