50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
#!/usr/bin/env python3
|
|
import json
|
|
import sys
|
|
|
|
def fix_names(obj):
|
|
"""
|
|
Recursively traverse obj (which may be a dict or list),
|
|
and whenever we find obj['meta']['name'], replace '-' with '_'.
|
|
"""
|
|
if isinstance(obj, dict):
|
|
# if this dict has a 'meta' sub-dict with a 'name' key, fix it
|
|
meta = obj.get("meta")
|
|
if isinstance(meta, dict) and "name" in meta:
|
|
name = meta["name"]
|
|
if isinstance(name, str) and "-" in name:
|
|
meta["name"] = name.replace("-", "_")
|
|
# recurse into all values
|
|
for v in obj.values():
|
|
fix_names(v)
|
|
|
|
elif isinstance(obj, list):
|
|
for item in obj:
|
|
fix_names(item)
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python3 process_json.py input.json [output.json]")
|
|
sys.exit(1)
|
|
|
|
in_path = sys.argv[1]
|
|
out_path = sys.argv[2] if len(sys.argv) >= 3 else None
|
|
|
|
# load
|
|
with open(in_path, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
# process
|
|
fix_names(data)
|
|
|
|
# write
|
|
if out_path:
|
|
with open(out_path, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
print(f"Processed JSON written to {out_path}")
|
|
else:
|
|
print(json.dumps(data, indent=2, ensure_ascii=False))
|
|
|
|
if __name__ == "__main__":
|
|
main()
|