Miscellaneous¶
-
pheres._misc.
FlatKey
¶ Typehint for keys of flattened JSON
alias of Tuple[Union[int, str], …]
-
pheres._misc.
FlatJSON
¶ Type hint of a flattened JSON
alias of Dict[Tuple[Union[int, str], …], Union[None, bool, int, float, str, pheres._typing.JsonableValue]]
-
pheres._misc.
flatten
(obj: JSONObject) → FlatJSON¶ Flattens a JSON object to a dict with a single level of mapping. Key become tuples that store the path from the top-level object down to the value. Object keys are stored as str, Array index as int
- Parameters
obj – json object to flatten
- Returns
A dict mapping tuples of index and key to the final value
-
pheres._misc.
expand
(flat_json: FlatJSON, *, array_as_dict: bool = False, sort: bool = True) → JSONObject¶ Expand a flat JSON back into a JSON object. This is the inverse operation of flatten(). If there are duplicated values under the same key, a random one is kept
- Parameters
flat_json – flat json to expand
array_as_dict – whether to represent arrays as dict[int, JSONValue] instead of list
sort – whether to sort JSONObject by keys
- Returns
A JSON object that is the expanded representation of the flat_json
- Raises
ValueError – the flat_json is invalid. See the error for details
-
pheres._misc.
compact
(obj: JSONObject, *, sep='.') → JSONObject¶ Removes unnecessary levels in the JSON tree
Returns a new JSONObject where keys with only one element are merged with their parent key. Keys are converted to
str
objects. The returned value contains only dicts, even if the original JSON contained arrays.- Parameters
obj – json object object to compact
sep – separator to use for merging keys
- Returns
A compact, dict-only, representation of json_obj
-
pheres._misc.
get
(obj: Union[JSONArray, JSONObject], key: Union[int, str, FlatKey], default=MISSING) → JSONType¶ Retrieve a value on a JSON array or object. Return
default
if it was provided andkey
is missing- Parameters
obj – JSON array or object to retrieve the value from
key – key to index. Supports iterable of successive keys
default – optional value to return if
key
is missing
- Raises
JSONKeyError –
key
is missing anddefault
was not specified
-
pheres._misc.
has
(obj: Union[JSONArray, JSONObject], key: Union[int, str, FlatKey])¶ Test if a JSON has the provided key
Implemented by calling
get(obj, key)
and catching JSONKeyErrorSee also
-
pheres._misc.
set
(obj: Union[JSONArray, JSONObject], key: Union[int, str, FlatKey], value: JSONObject)¶ Sets the value of the key in the JSON
Possibly creates the full path at once. Setting a value in a array past its length or adding an element at the end is supported
- Parameters
- Raises
IndexError – The key is not valid