Skip to content

Commit 2e2a0e6

Browse files
committed
ENH: Add .text and .json() accessors for ease
1 parent bb8b808 commit 2e2a0e6

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

nibabel/nifti1.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
from __future__ import annotations
1515

16+
import json
1617
import typing as ty
1718
import warnings
1819
from io import BytesIO
@@ -368,16 +369,38 @@ def get_code(self):
368369
"""Return the canonical extension type code."""
369370
return self.code
370371

372+
# Canonical access to extension content
373+
# Follows the lead of httpx.Response .content, .text and .json()
374+
# properties/methods
371375
@property
372376
def content(self) -> bytes:
373377
"""Return the extension content as raw bytes."""
374378
self._sync()
375379
return self._content
376380

381+
@property
382+
def text(self) -> str:
383+
"""Attempt to decode the extension content as text.
384+
385+
The encoding is determined by the `encoding` attribute, which may be
386+
set by the user or subclass. If not set, the default encoding is 'utf-8'.
387+
"""
388+
return self.content.decode(self.encoding or 'utf-8')
389+
390+
def json(self) -> ty.Any:
391+
"""Attempt to decode the extension content as JSON.
392+
393+
If the content is not valid JSON, a JSONDecodeError or UnicodeDecodeError
394+
will be raised.
395+
"""
396+
return json.loads(self.content)
397+
377398
def get_content(self) -> T:
378399
"""Return the extension content in its runtime representation.
379400
380401
This method may return a different type for each extension type.
402+
For simple use cases, consider using ``.content``, ``.text`` or ``.json()``
403+
instead.
381404
"""
382405
if self._object is None:
383406
self._object = self._unmangle(self._content)

0 commit comments

Comments
 (0)