forked from spdx/tools-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_parser.py
More file actions
35 lines (25 loc) · 1.09 KB
/
json_parser.py
File metadata and controls
35 lines (25 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# SPDX-FileCopyrightText: 2022 spdx contributors
#
# SPDX-License-Identifier: Apache-2.0
import json
from beartype.typing import Any, Dict
from spdx_tools.spdx.model import Document
from spdx_tools.spdx.parser.jsonlikedict.json_like_dict_parser import JsonLikeDictParser
# chars we don't want to see in SBOMs
CONTROL_CHARS_MAP = {
8: None, # ASCII/UTF-8: backspace
12: None, # ASCII/UTF-8: formfeed
}
def remove_control_chars_from_value(value: Any) -> Any:
if isinstance(value, str):
return value.translate(CONTROL_CHARS_MAP)
elif isinstance(value, list):
for i in range(len(value)):
value[i] = remove_control_chars_from_value(value[i])
return value
def remove_json_control_chars_hook(pairs: list) -> dict:
return {k: remove_control_chars_from_value(v) for k, v in pairs}
def parse_from_file(file_name: str, encoding: str = "utf-8") -> Document:
with open(file_name, encoding=encoding) as file:
input_doc_as_dict: Dict = json.load(file, object_pairs_hook=remove_json_control_chars_hook)
return JsonLikeDictParser().parse(input_doc_as_dict)