I think it would be easier to use your dict
directly.
data = {
"1": {"b": 1}
}
some_value = data["1"]["b"]
If you want to use SimpleNamespace
you need to replace 1
with something like _1
to be able to use something like x._1.b
because x.1.b
raises a syntax error.
This can be done by recursively converting your dict to a SimpleNamespace
object and inserting _
in all keys starting with a number.
def dict_to_namespace(d):
return SimpleNamespace(
**{
(f"_{k}" if k[0].isdecimal() else k): (
dict_to_namespace(v) if isinstance(v, dict) else v
)
for k, v in d.items()
}
)
x = dict_to_namespace(data)
some_value = x._1.b
Note: this will lead to errors if your dict/json keys contain special characters (spaces, dashes etc.)