-1

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.

1110
  • 7,829
  • 55
  • 176
  • 334

1 Answers1

0

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

matszwecja
  • 6,357
  • 2
  • 10
  • 17