I'm new in python, I have a json with int as key values such as this:
"data": {
"1": {
"b": 1
}
}
I want to cast it to object:
x = json.loads(json.dumps(data, indent=4, sort_keys=True), object_hook=lambda d: SimpleNamespace(**d))
now I want to access to b . how should I do that . this code returns error:
x.1.b
CodePudding user response:
In Python, variables are not allowed to start with a number.
getattr(x, "1").b
https://docs.python.org/3/library/functions.html#getattr
Related post: Can variable names in Python start with an integer?
CodePudding user response:
I think it would be easier to use your dict
directly.
data = {
"1": {"b": 1}
}
x = data["1"]["b"]