Skip to content

Instantly share code, notes, and snippets.

@Jan200101
Created January 13, 2022 08:20
Show Gist options
  • Select an option

  • Save Jan200101/9b8655e3fc96f305e4e84c5b2f7ef78c to your computer and use it in GitHub Desktop.

Select an option

Save Jan200101/9b8655e3fc96f305e4e84c5b2f7ef78c to your computer and use it in GitHub Desktop.
little srip
import json
import os
from typing import Union
INDENTION_SIZE = 4
INDENTION_CHAR = " "
TYPE_TO_STR = {
int: "int",
str: "char*",
float: "float",
bool: "bool",
None.__class__: "void*"
}
def normalize_name(val: str) -> str:
val = val.replace(" ", "_")
return val
def normalize_filename(val: str) -> str:
val = ".".join(val.split(".")[:-1])
val = val.replace(os.path.sep, "_")
val = normalize_name(val)
return val
def gen_struct(filepath: str) -> str:
with open(filepath) as file:
data = json.load(file)
name = normalize_filename(os.path.basename(filepath))
output = f"struct {name}\n" + "{\n"
output += gen_struct_inner(data)
output += "};"
return output
def gen_struct_inner(data: Union[dict, list], _level: int = 1) -> str:
indention = INDENTION_CHAR * (INDENTION_SIZE * _level)
output = ""
for key, val in data.items():
key = normalize_name(key)
if key in TYPE_TO_STR.values():
raise SyntaxError(f"{key} cannot be a key")
elif type(val) in TYPE_TO_STR:
output += indention + f"{TYPE_TO_STR[type(val)]} {key}; // = {val}\n"
elif isinstance(val, dict):
output += indention + "struct\n" + indention + "{\n"
output += gen_struct_inner(val, _level=_level+1)
output += indention + "} " + f"{key};\n"
elif isinstance(val, list):
item = val[0]
if type(item) in TYPE_TO_STR:
output += indention + f"{TYPE_TO_STR[type(item)]}* {key}; // = {set(val)}\n"
elif isinstance(item, dict):
output += indention + "struct\n" + indention + "{\n"
output += gen_struct_inner(item, _level=_level+1)
output += indention + "} " + f"{key};\n"
else:
raise TypeError(f"Unknown type {val.__class__.__name__}")
return output
print(gen_struct("data.json"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment