summaryrefslogtreecommitdiffstats
path: root/Doc/library/json.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2022-08-23 21:22:00 (GMT)
committerGitHub <noreply@github.com>2022-08-23 21:22:00 (GMT)
commit1f0eafa844bf5a380603d55e8d4b42d8c2a3439d (patch)
tree7d0baf97bbdeb48afea0e1685ce49b17f3855d95 /Doc/library/json.rst
parent054328f0dd3e9ee5a8a026dfcfa606baf7e9f052 (diff)
downloadcpython-1f0eafa844bf5a380603d55e8d4b42d8c2a3439d.zip
cpython-1f0eafa844bf5a380603d55e8d4b42d8c2a3439d.tar.gz
cpython-1f0eafa844bf5a380603d55e8d4b42d8c2a3439d.tar.bz2
GH-96145: Add AttrDict to JSON module for use with object_hook (#96146)
Diffstat (limited to 'Doc/library/json.rst')
-rw-r--r--Doc/library/json.rst43
1 files changed, 43 insertions, 0 deletions
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
index f65be85..467d5d9 100644
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -9,6 +9,11 @@
**Source code:** :source:`Lib/json/__init__.py`
+.. testsetup:: *
+
+ import json
+ from json import AttrDict
+
--------------
`JSON (JavaScript Object Notation) <https://json.org>`_, specified by
@@ -532,6 +537,44 @@ Exceptions
.. versionadded:: 3.5
+.. class:: AttrDict(**kwargs)
+ AttrDict(mapping, **kwargs)
+ AttrDict(iterable, **kwargs)
+
+ Subclass of :class:`dict` object that also supports attribute style dotted access.
+
+ This class is intended for use with the :attr:`object_hook` in
+ :func:`json.load` and :func:`json.loads`::
+
+ .. doctest::
+
+ >>> json_string = '{"mercury": 88, "venus": 225, "earth": 365, "mars": 687}'
+ >>> orbital_period = json.loads(json_string, object_hook=AttrDict)
+ >>> orbital_period['earth'] # Dict style lookup
+ 365
+ >>> orbital_period.earth # Attribute style lookup
+ 365
+ >>> orbital_period.keys() # All dict methods are present
+ dict_keys(['mercury', 'venus', 'earth', 'mars'])
+
+ Attribute style access only works for keys that are valid attribute
+ names. In contrast, dictionary style access works for all keys. For
+ example, ``d.two words`` contains a space and is not syntactically
+ valid Python, so ``d["two words"]`` should be used instead.
+
+ If a key has the same name as a dictionary method, then a dictionary
+ lookup finds the key and an attribute lookup finds the method:
+
+ .. doctest::
+
+ >>> d = AttrDict(items=50)
+ >>> d['items'] # Lookup the key
+ 50
+ >>> d.items() # Call the method
+ dict_items([('items', 50)])
+
+ .. versionadded:: 3.12
+
Standard Compliance and Interoperability
----------------------------------------