简体   繁体   English

如何从python中的json提取属性

[英]How to extract attribute from json in python

I created a json and passed it do a function.我创建了一个 json 并传递给它做一个 function。
But when I try to extract data it doesn't work.但是当我尝试提取数据时它不起作用。

data = {}
data['unit'] = { "id": "052e8reb-d801-89g6-8b26-3bd2da914890" }

test_data(data)

def test_data(data: dict):
    getattr(data.unit, 'id', None)
    getattr(data.get("unit", None), 'id', None)
    data.get('unit').get('id', None)

All three methods fail.这三种方法都失败了。 What should I do to safe get id if unit is not None .如果unit不是None ,我应该怎么做才能安全获取id
I am new to python.我是 python 的新用户。

First of all, that's not JSON - that's a dictionary.首先,那不是 JSON——那是一本字典。 So, you can use it like a standard dictionary - data['unit']['id'] - equivalent to last line (except for if the key is not found), which should work因此,您可以像标准字典一样使用它 - data['unit']['id'] - 相当于最后一行(除非找不到密钥),它应该可以工作

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

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