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 hashes)

Uploaded Source

Built Distribution

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

Uploaded Python 3

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