Skip to main content

jsonpath_ng with extended functionality

Project description

jsonpath-extensions

Provides new Extensions to the jsonpath_ng python library to provide commonly requested functions. The context for these functions is always the value provided from the resolution of the provided jsonpath. The functions will all handle lists or single values as inputs unless explicitly marked. If you're confused about a function's intended, behavior take a look at the tests.

Usage

from eha_jsonpath import parse
# The following is pseudocode, don't copy it.
obj = {'my': 'object'}
path = '$.some.jsonpath.`fn(arg1, arg2)`'
matches = parse(path).find(obj)

New Extensions

Cast

Attempts to apply a cast to the result of a jsonpath expression. Will operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`cast({castType})`

supported castTypes and behavior:

CASTS = {
    'int': lambda x: _cast_int(x),  # see below
    'boolean': lambda x: bool(x),
    'string': lambda x: str(x),
    'float': lambda x: float(x),
    'json': lambda x: json.loads(x),  # standard json library
    'none': lambda x: x,
    'null': lambda x: None
}


def _cast_int(obj):
    # fixes issues when trying to cast a float str -> int
    # int('1.09') throws ValueError
    try:
        return int(obj)
    except ValueError:
        return int(float(obj))

Split List

Takes a string at a given jsonpath and attempts to split it into an array of given delimiter and casts the array items to a specific castType. See valid casts in Cast section.

The resolved path must be a string. Will not operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`splitlist({delimiter}, {castType})`

Match

Checks the value found at a jsonpath against a provided match_term. If the value is not found, returns the null_value. Will operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`match({match_term}, {null_value})`

White space after commas is required!

behavior:

result = (value == match_term) if value != None else null_value

Not Match

Provides the inverse of Match. Checks the value found at a jsonpath against a provided match_term. If the value is not found, returns the null_value. Will operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`notmatch({match_term}, {null_value})`

White space after commas is required!

behavior:

result = (value != match_term) if value != None else null_value

Parse Datetime

Attempts to parse the iso formatted datetime from a string found at a given jsonpath. Then returns a part or the whole of the parsed datetime as specified by a python array slice. Will operate invidiually on array items in the case the path resolves to an array. The strptime_str format is taken from the python strptime behavior. The array slice notation used in return_slice is uses the standard slice operator, with semi-colon delimited arguments like:

def args_to_slice(cls, return_slice, obj):
    defaults = [0, None, None]
    parts = []
    for x, i in enumerate(return_slice.split(':')):
        try:
            parts.append(int(i))
        except ValueError:
            parts.append(defaults[x])
    return obj[slice(*parts)]

usage: $.my.path.`datetime({strptime_str}, {return_slice})`

White space after commas is required!

Hash

Returns a 128bit, hex formatted MD5 hash of the value of a resolved jsonpath added to a provided salt. This is useful for generating a UUID compatable value from a piece of source information along with some unique salt. This allows for a non-UUID foreign key to be reliably converted to the same UUID compatable value every time. Will operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`hash({salt})`

Template

Will substitue the value found at a resolved jsonpath into a formatted string with a singe replacement place holder. Will operate invidiually on array items in the case the path resolves to an array.

usage: Using of format resembling: my name is {}

$.my.path.`template({template_format)`

Value Replace

Replaces resolved values matching match_value with replacement_value. Will operate invidiually on array items in the case the path resolves to an array.

usage: $.my.path.`valuereplace({match_value}, {replacement_value})`

White space after commas is required!

behavior:

replacement_value if (match_value == value) else value

Dictionary Replace

Replaces resolved values matching a key in a passed dictionary with the appropriate value from the same dictionary. Will operate invidiually on array items in the case the path resolves to an array. The dictionary argument should be a stringified python dictionary.

usage: $.my.path.`dictionaryreplace({stringified_python_dictionary})` result is: path value replaces with value of matching key in dictionary

behavior:

return passed_dict.get(value, None)

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

eha_jsonpath-0.5.1-py2.py3-none-any.whl (9.7 kB view details)

Uploaded Python 2Python 3

File details

Details for the file eha_jsonpath-0.5.1-py2.py3-none-any.whl.

File metadata

  • Download URL: eha_jsonpath-0.5.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.1

File hashes

Hashes for eha_jsonpath-0.5.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 1d356b89c4d21a1dc581634f529ea0ecaf4e324e0a5f8e3e652d7c2048bfc35d
MD5 d2849ae8df380cff5740df563e0b1d4e
BLAKE2b-256 0f44eee5a7da478b276f6f1d9f6e70ecdc06af418db2ffd590369142a0d5f932

See more details on using hashes here.

Supported by

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