-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.py
More file actions
53 lines (44 loc) · 1.72 KB
/
transform.py
File metadata and controls
53 lines (44 loc) · 1.72 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
JSON transformation module using jsonbender library.
This module reads a YAML mapping file and applies transformations to JSON data.
"""
import json
import yaml
from jsonbender import bend
def safe_eval_mapping(expression):
"""
Safely evaluate string expressions for jsonbender mappings.
This is a simplified version that handles basic jsonbender expressions.
"""
# For now, return the string as-is since eval is unsafe
# In a production environment, you'd want to implement proper parsing
# or use a safer evaluation method
return expression
def main():
"""Main function to perform JSON transformation."""
try:
with open("mapping.yaml", "r", encoding="utf-8") as file:
mappingfile = yaml.load(file, Loader=yaml.FullLoader)
mapping = {}
for key, value in mappingfile.items():
if isinstance(value, str):
# Using safe_eval_mapping instead of eval
mapping[key] = safe_eval_mapping(value)
else:
mapping[key] = value
with open('input.json', 'r', encoding="utf-8") as source_file:
source = json.load(source_file)
result = bend(mapping, source)
with open('output.json', 'w', encoding="utf-8") as output_file:
json.dump(result, output_file)
print(json.dumps(result))
except FileNotFoundError as e:
print(f"Error: Required file not found - {e}")
except yaml.YAMLError as e:
print(f"Error: Invalid YAML format - {e}")
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON format - {e}")
except (OSError, IOError) as e:
print(f"Error: File operation failed - {e}")
if __name__ == "__main__":
main()