Extract nested value from json-like dict by providing sequence of keys
Project description
>>> extract_nested_value({1: {2: {3: "value"}}}, [1, 2, 3])
"value
Extracts a nested value from a JSON-like dict by specifying a sequence of keys.
May be useful to avoid a KeyError exception when accessing JSON-like dicts with a dynamic nested structure, when you know the key paths of elements, but are unsure whether elements exist.
Returns the nested value or None if it wasn't found. Could throw a KeyError exception if strict=True
is passed.
Examples
>>> extract_nested_value({1: 2}, [1])
2
>>> extract_nested_value({1: {2: {3: "value"}}}, [1, 2, 3])
"value"
>>> extract_nested_value({1: 2}, ["a"])
None
>>> extract_nested_value({1: 2}, [])
{1: 2}
>>> extract_nested_value({1: 2}, ["a"], strict=True)
KeyError: "Keys sequence '["a"]' do not exists in object '{1: 2}'")
Arguments
json_obj
: JSON-like dict from which the nested value should be extractedkeys
: ordered sequence of keys to derive the nested valuestrict
: (defaultFalse
) prevents throwing an exception when keys are not exist in nested object when set toFalse
. ThrowsKeyError
exception if set toTrue
and key wasn't found.
Returns
Nested value, if the entire chain of keys is present, or None
Development
Look at Makefile
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file nested-value-extractor-0.2.0.tar.gz
.
File metadata
- Download URL: nested-value-extractor-0.2.0.tar.gz
- Upload date:
- Size: 4.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.12.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 594cdfb40c36697c78a877b0ba6cb8ec4ef39d03854003a1c346f99f001be167 |
|
MD5 | fc272ac386dd1e9fd77b7c85641ce38e |
|
BLAKE2b-256 | 2ced8e80ba9bbc2b66dd1f57c189377c9af1683af5fd80c91a97f680c825cd2f |
File details
Details for the file nested_value_extractor-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: nested_value_extractor-0.2.0-py3-none-any.whl
- Upload date:
- Size: 3.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.12.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 71b9b80ea46b1134978038168e8bc142c5282cdf933c08102e0a0b7e97761e14 |
|
MD5 | b394f79c16ca22bf11977daf0b728aaf |
|
BLAKE2b-256 | 14eb6211bab9c39790fd85aa189a819547fa4bf4e64d5b988e6439b0d6c9f301 |