or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdjsonpointer-class.md

jsonpointer-class.mddocs/

0

# JsonPointer Class

1

2

The JsonPointer class provides an object-oriented interface for JSON pointer operations, offering advanced functionality for complex pointer manipulation, path operations, and step-by-step document navigation.

3

4

## Capabilities

5

6

### Construction and Basic Operations

7

8

Create JsonPointer instances and perform core resolution and modification operations.

9

10

```python { .api }

11

class JsonPointer:

12

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

13

14

def __init__(self, pointer):

15

"""

16

Creates a JsonPointer from string representation.

17

18

Args:

19

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

20

21

Raises:

22

JsonPointerException: If pointer format is invalid or contains invalid escapes

23

"""

24

25

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

26

"""

27

Resolves the pointer against doc and returns the referenced object.

28

29

Args:

30

doc: JSON document to resolve against

31

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

32

If not provided, raises JsonPointerException on missing paths.

33

34

Returns:

35

The referenced object or default value

36

37

Raises:

38

JsonPointerException: If pointer cannot be resolved and no default provided

39

"""

40

41

# Alias for resolve method

42

get = resolve

43

44

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

45

"""

46

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

47

48

Args:

49

doc: JSON document to modify

50

value: Value to set at the pointer location

51

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

52

53

Returns:

54

Modified document (original if inplace=True, deep copy if inplace=False)

55

56

Raises:

57

JsonPointerException: Cannot set root in place, or other resolution errors

58

"""

59

```

60

61

### Path Properties and Inspection

62

63

Access the pointer's path information and internal structure.

64

65

```python { .api }

66

class JsonPointer:

67

@property

68

def path(self):

69

"""

70

Returns the string representation of the pointer.

71

72

Returns:

73

str: The pointer path with proper escaping (e.g., '/foo/~0/~1')

74

"""

75

76

parts

77

"""

78

List of unescaped pointer parts (instance attribute).

79

80

Type: list of str

81

Description: List of unescaped path components that make up this pointer.

82

For example, JsonPointer("/foo/bar/0").parts == ["foo", "bar", "0"]

83

"""

84

85

def get_parts(self):

86

"""

87

Returns the list of the parts.

88

89

Returns:

90

list: List of unescaped path components (same as .parts property)

91

"""

92

```

93

94

### Advanced Navigation

95

96

Perform step-by-step document navigation and partial resolution.

97

98

```python { .api }

99

class JsonPointer:

100

def to_last(self, doc):

101

"""

102

Resolves ptr until the last step, returns (sub-doc, last-step).

103

104

Args:

105

doc: JSON document to navigate

106

107

Returns:

108

tuple: (parent_document, final_key_or_index) for the target location

109

"""

110

111

def walk(self, doc, part):

112

"""

113

Walks one step in doc and returns the referenced part.

114

115

Args:

116

doc: Current document/object

117

part (str): Path component to navigate (unescaped)

118

119

Returns:

120

Next level object or EndOfList for array "-" access.

121

For mappings: doc[part]

122

For sequences: doc[int(part)] or EndOfList(doc) if part is "-"

123

For duck-typed objects: doc[part] using __getitem__

124

125

Raises:

126

JsonPointerException: If navigation fails (missing key, invalid index, etc.)

127

"""

128

129

@classmethod

130

def get_part(cls, doc, part):

131

"""

132

Returns the next step in the correct type for accessing the document.

133

134

Args:

135

doc: Document to determine access type for (dict, list, or __getitem__ object)

136

part (str): String part to convert to appropriate type

137

138

Returns:

139

Properly typed key:

140

- str for Mapping objects (dicts)

141

- int for Sequence objects (lists) when part is numeric

142

- str "-" for Sequence objects when part is "-" (end-of-list)

143

- original str for duck-typed objects with __getitem__

144

145

Raises:

146

JsonPointerException: If part is not valid for the document type

147

(e.g., non-numeric index for arrays, unsupported object type)

148

"""

149

```

150

151

### Pointer Operations

152

153

Manipulate and combine pointers using containment checking and path joining.

154

155

```python { .api }

156

class JsonPointer:

157

def contains(self, ptr):

158

"""

159

Returns True if self contains the given ptr.

160

161

Args:

162

ptr (JsonPointer): Pointer to check for containment

163

164

Returns:

165

bool: True if this pointer contains the given pointer

166

"""

167

168

def __contains__(self, item):

169

"""

170

Returns True if self contains the given ptr (supports 'in' operator).

171

172

Args:

173

item (JsonPointer): Pointer to check for containment

174

175

Returns:

176

bool: True if this pointer contains the given pointer

177

"""

178

179

def join(self, suffix):

180

"""

181

Returns a new JsonPointer with the given suffix appended to this ptr.

182

183

Args:

184

suffix: JsonPointer, str, or list of parts to append

185

186

Returns:

187

JsonPointer: New pointer with suffix appended

188

189

Raises:

190

JsonPointerException: If suffix is invalid

191

"""

192

193

def __truediv__(self, suffix):

194

"""

195

Support for '/' operator (Python 3) - same as join().

196

197

Args:

198

suffix: Suffix to append

199

200

Returns:

201

JsonPointer: New pointer with suffix appended

202

"""

203

```

204

205

### Class Methods and Construction

206

207

Alternative construction methods for creating pointers from parts.

208

209

```python { .api }

210

class JsonPointer:

211

@classmethod

212

def from_parts(cls, parts):

213

"""

214

Constructs a JsonPointer from a list of (unescaped) paths.

215

216

Args:

217

parts (list): List of unescaped path components

218

219

Returns:

220

JsonPointer: New pointer constructed from parts

221

"""

222

```

223

224

### Comparison and Hashing

225

226

Support for pointer comparison, hashing, and string representation.

227

228

```python { .api }

229

class JsonPointer:

230

def __eq__(self, other):

231

"""

232

Compares a pointer to another object.

233

234

Args:

235

other: Object to compare with

236

237

Returns:

238

bool: True if both are JsonPointers with identical parts

239

"""

240

241

def __hash__(self):

242

"""

243

Returns hash of the pointer for use in sets and as dict keys.

244

245

Returns:

246

int: Hash value based on pointer parts

247

"""

248

249

def __str__(self):

250

"""

251

Returns string representation of the pointer.

252

253

Returns:

254

str: The pointer path (same as .path property)

255

"""

256

257

def __repr__(self):

258

"""

259

Returns debug representation of the pointer.

260

261

Returns:

262

str: Debug string like 'JsonPointer("/foo/bar")'

263

"""

264

```

265

266

## Usage Examples

267

268

### Basic Operations

269

270

```python

271

from jsonpointer import JsonPointer

272

273

doc = {"users": [{"name": "Alice"}, {"name": "Bob"}]}

274

275

# Create pointer

276

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

277

278

# Resolve value

279

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

280

# or using alias

281

name = ptr.get(doc) # "Alice"

282

283

# Set value

284

ptr.set(doc, "Alice Smith") # Modifies doc in place

285

286

# Set without modifying original

287

new_doc = ptr.set(doc, "Alice Johnson", inplace=False)

288

```

289

290

### Path Inspection

291

292

```python

293

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

294

295

# Get path components

296

print(ptr.path) # "/users/0/name"

297

print(ptr.parts) # ["users", "0", "name"]

298

print(ptr.get_parts()) # ["users", "0", "name"]

299

```

300

301

### Advanced Navigation

302

303

```python

304

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

305

306

# Navigate to parent

307

parent, final_key = ptr.to_last(doc)

308

# parent = {"name": "Alice"}, final_key = "name"

309

310

# Step-by-step navigation

311

current = doc

312

for part in ptr.parts:

313

current = ptr.walk(current, part)

314

# current = "Alice"

315

```

316

317

### Pointer Composition

318

319

```python

320

base = JsonPointer("/users")

321

index = JsonPointer("/0")

322

field = JsonPointer("/name")

323

324

# Join pointers

325

user_ptr = base.join(index) # "/users/0"

326

name_ptr = user_ptr.join(field) # "/users/0/name"

327

328

# Using / operator (Python 3)

329

name_ptr2 = base / index / field # "/users/0/name"

330

331

# From parts

332

parts = ["users", "0", "name"]

333

ptr = JsonPointer.from_parts(parts) # "/users/0/name"

334

```

335

336

### Containment and Comparison

337

338

```python

339

parent = JsonPointer("/users/0")

340

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

341

342

# Check containment

343

print(parent.contains(child)) # True

344

print(child in parent) # True (using __contains__)

345

346

# Pointer comparison

347

ptr1 = JsonPointer("/users/0")

348

ptr2 = JsonPointer("/users/0")

349

print(ptr1 == ptr2) # True

350

351

# Use as dict keys (hashable)

352

pointer_cache = {ptr1: "cached_value"}

353

```

354

355

### Error Handling

356

357

```python

358

from jsonpointer import JsonPointer, JsonPointerException

359

360

try:

361

# Invalid pointer format

362

bad_ptr = JsonPointer("invalid") # Must start with '/'

363

except JsonPointerException as e:

364

print(f"Invalid pointer: {e}")

365

366

try:

367

# Missing path with no default

368

ptr = JsonPointer("/missing/path")

369

value = ptr.resolve(doc)

370

except JsonPointerException as e:

371

print(f"Path not found: {e}")

372

373

# Safe resolution with default

374

value = ptr.resolve(doc, "default_value")

375

```

376

377

### Special Array Operations

378

379

```python

380

doc = {"items": [1, 2, 3]}

381

382

# Access array elements

383

ptr = JsonPointer("/items/0")

384

first = ptr.resolve(doc) # 1

385

386

# Access end of array (for appending)

387

end_ptr = JsonPointer("/items/-")

388

end_ref = end_ptr.resolve(doc) # EndOfList object

389

390

# Append to array using set

391

end_ptr.set(doc, 4) # doc becomes {"items": [1, 2, 3, 4]}

392

```