Skip to main content

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 extracted
  • keys: ordered sequence of keys to derive the nested value
  • strict: (default False) prevents throwing an exception when keys are not exist in nested object when set to False. Throws KeyError exception if set to True and key wasn't found.

Returns

Nested value, if the entire chain of keys is present, or None

Development

Look at Makefile

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nested-value-extractor-0.2.0.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

nested_value_extractor-0.2.0-py3-none-any.whl (3.9 kB view details)

Uploaded Python 3

File details

Details for the file nested-value-extractor-0.2.0.tar.gz.

File metadata

File hashes

Hashes for nested-value-extractor-0.2.0.tar.gz
Algorithm Hash digest
SHA256 594cdfb40c36697c78a877b0ba6cb8ec4ef39d03854003a1c346f99f001be167
MD5 fc272ac386dd1e9fd77b7c85641ce38e
BLAKE2b-256 2ced8e80ba9bbc2b66dd1f57c189377c9af1683af5fd80c91a97f680c825cd2f

See more details on using hashes here.

File details

Details for the file nested_value_extractor-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for nested_value_extractor-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 71b9b80ea46b1134978038168e8bc142c5282cdf933c08102e0a0b7e97761e14
MD5 b394f79c16ca22bf11977daf0b728aaf
BLAKE2b-256 14eb6211bab9c39790fd85aa189a819547fa4bf4e64d5b988e6439b0d6c9f301

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page