'How to extract attribute from json in python
I created a json and passed it do a 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.
I am new to python.
Solution 1:[1]
First of all, that's not JSON - that's a dictionary.
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | matszwecja |
