简体   繁体   English

将json转换为python中的对象,以数字为键

[英]convert json to object in python with numbers as key

I'm new in python, I have a json with int as key values such as this:我是 Python 新手,我有一个以 int 为键值的 json,例如:

"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 .现在我想访问 b 。 how should I do that .我该怎么做。 this code returns error:此代码返回错误:

x.1.b x.1.b

I think it would be easier to use your dict directly.我认为直接使用你的dict会更容易。

data = {
    "1": {"b": 1} 
}

x = data["1"]["b"]

In Python, variables are not allowed to start with a number.在 Python 中,变量不允许以数字开头。

getattr(x, "1").b

https://docs.python.org/3/library/functions.html#getattr https://docs.python.org/3/library/functions.html#getattr

Related post: Can variable names in Python start with an integer?相关文章: Python 中的变量名可以以整数开头吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM