Skip to content

Commit 20de3f1

Browse files
committed
initial commit
1 parent 2eb3845 commit 20de3f1

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13

pyproject.toml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
[project]
2+
name = "jsonchain"
3+
readme = "README.md"
4+
dynamic = ["version", "description"]
5+
authors = [
6+
{ name = "Connor Ferster", email = "connor@structuralpython.com" }
7+
]
8+
requires-python = ">=3.10"
9+
dependencies = []
10+
11+
[project.scripts]
12+
jsonchain = "jsonchain:main"
13+
14+
[build-system]
15+
requires = ["flit_core >=3.2,<4"]
16+
build-backend = "flit_core.buildapi"

src/jsonchain/__init__.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)