|
| 1 | +import json |
| 2 | +import pathlib |
| 3 | +from typing import Any, Optional |
| 4 | + |
| 5 | +def load_json(filepath: str | pathlib.Path) -> dict | list: |
| 6 | + """ |
| 7 | + Loads the JSON data at 'filepath' into a Python object. |
| 8 | + """ |
| 9 | + with open(filepath, 'r') as file: |
| 10 | + return json.load(file) |
| 11 | + |
| 12 | + |
| 13 | +def dump_json(object: list | dict, filepath: str | pathlib.Path) -> None: |
| 14 | + """ |
| 15 | + Dumps the 'object' (which must be JSON-serializable) into a JSON |
| 16 | + file at 'filepath'. |
| 17 | + """ |
| 18 | + with open(filepath, 'w') as file: |
| 19 | + json.dump(object, file) |
| 20 | + |
| 21 | + |
| 22 | +def extract_keys( |
| 23 | + object: dict[str, Any], |
| 24 | + key_name: str, |
| 25 | + include_startswith: Optional[str] = None, |
| 26 | + exclude_startswith: Optional[str] = None, |
| 27 | + ) -> list[dict[str, Any]]: |
| 28 | + """ |
| 29 | + Returns a list of dicts where each dict has a key of 'key_name' |
| 30 | + and a value of one of the keys of 'object'. |
| 31 | +
|
| 32 | + e.g. |
| 33 | + object = {"key1": value, "key2": value, "key3": value} |
| 34 | + key_name = "label" |
| 35 | +
|
| 36 | + extract_keys(object, key_name) # [{"label": "key1"}, {"label": "key2"}, {"label": "key3"}] |
| 37 | +
|
| 38 | + 'include_startswith': If provided, will only include keys that start with this string. |
| 39 | + 'exclude_startswith': If provided, will exclude all keys that start with this string. |
| 40 | +
|
| 41 | + If both 'include_startswith' and 'exclude_startswith' are provided, exclude is executed |
| 42 | + first. |
| 43 | + """ |
| 44 | + shortlist = [] |
| 45 | + for key in object.keys(): |
| 46 | + if exclude_startswith is not None and key.startswith(exclude_startswith): |
| 47 | + continue |
| 48 | + else: |
| 49 | + shortlist.append(key) |
| 50 | + |
| 51 | + acc = [] |
| 52 | + for key in shortlist: |
| 53 | + if include_startswith is not None and key.startswith(include_startswith): |
| 54 | + acc.append({key_name: key}) |
| 55 | + elif include_startswith is None: |
| 56 | + acc.append({key_name: key}) |
| 57 | + |
| 58 | + return acc |
| 59 | + |
| 60 | + |
0 commit comments