Coverage for src/python/ensembl/io/genomio/utils/json_utils.py: 100%
13 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-21 15:37 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-21 15:37 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Utils to deal with JSON files."""
17__all__ = ["get_json", "print_json"]
19import json
20from pathlib import Path
21from typing import Any
23from ensembl.utils import StrPath
26def get_json(src_path: StrPath, **kwargs: Any) -> Any:
27 """Generic data JSON loader.
29 Args:
30 src_path: Path to the JSON file to load.
32 """
33 with Path(src_path).open("r", encoding="utf-8") as json_file:
34 return json.load(json_file, **kwargs)
37def print_json(dst_path: StrPath, data: Any, **kwargs: Any) -> None:
38 """Generic data JSON dumper to a file, with keys sorted and pretty-printed with indent 4 by default.
40 Args:
41 dst_path: Path to the JSON file to create.
42 data: Any data to store into the file.
44 """
45 kwargs.setdefault("sort_keys", True)
46 kwargs.setdefault("indent", 4)
47 with Path(dst_path).open("w", encoding="utf-8") as json_file:
48 json_file.write(json.dumps(data, **kwargs))