module documentation

Utility functions for strings, JSON, and texts.

Function commentJson Add explanations for JSON attributes as comments to the end of the line.
Function findXPath Find a structured key in the dictionary dct. If key does not exists then default is returned.
Function flattenJSON Flatten a JSON string or dictionary.
Function isBase64 Validate that a value is in base64 encoded format.
Function isNumber Check whether a string contains a convertible number. This could be an integer or a float.
Function limitLines Limit the number of lines and the length of lines in a text.
Function parseJSONDecodingError Parse a JSON decoding error and return a readable error message including the error location.
Function removeCommentsFromJSON Remove comments from JSON string input.
Function setXPath Set a structured key and value in the dictionary dict.
Function simpleMatch Simple string match function.
Function soundex Convert a string to a Soundex value.
Function soundsLike Compare two strings using the soundex algorithm.
Function toHex Print a byte string as hex output, similar to the "od" command.
Variable _commentRegex Compiled regex expression of recognize comments.
Variable _decimalMatch Compiled regex expression of recognize decimal numbers in a string.
Variable _soundexReplacements Replacement characters for the soundex algorithm.
def commentJson(data: str | dict, explanations: dict[str, str], getAttributeValueName: Callable | None = lambda k, v: '', width: int | None = None) -> str:

Add explanations for JSON attributes as comments to the end of the line.

Parameters
data:str | dictThe JSON string or as a dictionary.
explanations:dict[str, str]A dictionary with the explanations. The keys must match the JSON keys.
getAttributeValueName:Callable | NoneA function that returns the named value of an attribute.
width:int | NoneOptional width of the output. If greater then the comment is put above the line.
Returns
strThe JSON string with comments.
def findXPath(dct: dict[str, Any], key: str, default: Any | None = None) -> Any | None:

Find a structured key in the dictionary dct. If key does not exists then default is returned.

  • It is possible to address a specific element in a list. This is done be
    specifying the element as "{n}".

Example

findXPath(resource, 'm2m:cin/{1}/lbl/{0}')

  • If an element is specified as "{}" then all elements in that list are returned in
    a list.

Example

findXPath(resource, 'm2m:cin/{1}/lbl/{}') or findXPath(input, 'm2m:cnt/m2m:cin/{}/rn')

  • If an element is specified as "{*}" and is targeting a dictionary then a single unknown key is
    skipped in the path. This can be used to skip, for example, unknown first elements in a structure. This is similar but not the same as "{0}" that works on lists.

Example

findXPath(resource, '{*}/rn')

Parameters
dct:dict[str, Any]Dictionary to search.
key:strKey with path to an attribute.
default:Any | NoneOptional return value if key is not found in dct
Returns
Any | NoneAny found value for the key path, or None resp. the provided default value.
def flattenJSON(data: str | dict) -> str:

Flatten a JSON string or dictionary.

Parameters
data:str | dictThe JSON string or as a dictionary.
Returns
strThe flattened JSON string.
def isBase64(value: str) -> bool:

Validate that a value is in base64 encoded format.

Parameters
value:strThe value to test.
Returns
boolBoolean indicating the test result.
def isNumber(string: Any) -> bool:

Check whether a string contains a convertible number. This could be an integer or a float.

Parameters
string:AnyThe string or object to check.
Returns
boolBoolean indicating the result of the test.
def limitLines(text: str, maxLines: int, cont: str = '...') -> str:

Limit the number of lines and the length of lines in a text.

Parameters
text:strThe text to limit.
maxLines:intThe maximum number of lines.
cont:strThe continuation string.
Returns
strThe limited text.
def parseJSONDecodingError(e: json.JSONDecodeError) -> str:

Parse a JSON decoding error and return a readable error message including the error location.

Parameters
e:json.JSONDecodeErrorThe JSON decoding error.
Returns
strA readable error message.
def removeCommentsFromJSON(data: str) -> str:

Remove comments from JSON string input.

This will remove:

  • /* multi-line comments */
  • // single-line comments
  • # single-line comments
  • ;; single-line comments

It will NOT remove:

  • String var1 = "this is /* not a comment. */";
  • char *var2 = "this is // not a comment, either.";
  • url = 'http://not.comment.com';
Parameters
data:strJSON string.
Returns
strJSON string without comments.
def setXPath(dct: dict[str, Any], key: str, value: Any | None = None, overwrite: bool | None = True, delete: bool | None = False) -> bool:

Set a structured key and value in the dictionary dict.

Create the attribute if necessary, and observe the overwrite option (True overwrites an existing key/value).

When the delete argument is set to True then the key attribute is deleted from the dictionary.

Examples

setXPath(aDict, 'a/b/c', 'aValue)

setXPath(aDict, 'a/{2}/c', 'aValue)

Retun:
Boolean indicating the success of the operation.
Parameters
dct:dict[str, Any]A dictionary in which to set or add the key and value.
key:strThe attribute's name to set in dct. This could by a path in dct, where the separator is a slash character (/). To address an element in a list, one can use the {n} operator in the path.
value:Any | NoneThe value to set for the attribute. Could be left out when deleting an attribute or value.
overwrite:bool | NoneIf True that overwrite an already existing value, otherwise skip.
delete:bool | NoneIf True then remove the atribute or list attribute key from the dictionary.
Returns
boolUndocumented
def simpleMatch(st: str, pattern: str, star: str | None = '*', ignoreCase: bool = False) -> bool:

Simple string match function.

This class supports the following expression operators:

  • '?' : any single character
  • '*' : zero or more characters
  • '+' : one or more characters
  • '[abc]' : any character in the set
  • '[^abc]' : any character not in the set
  • '\' : Escape an expression operator

A pattern must always match the full string st. This means that the pattern is implicit "^<pattern>$".

Examples

"hello" - "h?llo" -> True

"hello" - "h?lo" -> False

"hello" - "h*lo" -> True

"hello" - "h*" -> True

"hello" - "*lo" -> True

"hello" - "*l?" -> True

Parameters
st:strstring to test
pattern:strthe pattern string
star:str | Noneoptionally specify a different character as the star character
ignoreCase:boolignore case in the comparison
Returns
boolBoolean indicating a match.
def soundex(s: str, maxCount: int | None = 4) -> str:

Convert a string to a Soundex value.

Parameters
s:strThe string to convert.
maxCount:int | NoneUndocumented
Returns
strThe Soundex value as a string.
def soundsLike(s1: str, s2: str, maxCount: int | None = 4) -> bool:

Compare two strings using the soundex algorithm.

Parameters
s1:strFirst string to compare.
s2:strSecond string to compare.
maxCount:int | NoneMaximum number of soundex result characters to compare.
Returns
boolBoolean indicating the result of the comparison.
def toHex(bts: bytes, toBinary: bool | None = False, withLength: bool | None = False) -> str:

Print a byte string as hex output, similar to the "od" command.

Parameters
bts:bytesByte string to print.
toBinary:bool | NonePrint bytes as bit patterns.
withLength:bool | NoneAdditionally print length.
Returns
strFormatted string with the output.
_commentRegex =

Compiled regex expression of recognize comments.

_decimalMatch =

Compiled regex expression of recognize decimal numbers in a string.

_soundexReplacements: tuple =

Replacement characters for the soundex algorithm.