0

hi i am using api in my code that outputs in json format and it looks like this

{"rates":{"CZK":25.738},"base":"EUR","date":"2021-02-09"}

i want only the CZK part so 25.738 as output

i had tried this

def get_kurz():
    res = requests.get('https://api.exchangeratesapi.io/latest?symbols=CZK')
    kurz = json.loads(res.text)
    result = (kurz['CZK'])
    return(result)

but that didnt work closest i could get it to work was

def get_kurz():
    res = requests.get('https://api.exchangeratesapi.io/latest?symbols=CZK')
    kurz = json.loads(res.text)
    result = (kurz['rates'])
    return(result)

and that outputs

{'CZK': 25.738}

2 Answers2

1

For the dictionary object, you can use access the nested elements by using indexing multiple times.

So, for your dictionary object:

out = {"rates":{"CZK":25.738},"base":"EUR","date":"2021-02-09"}

If you want the value of CZK key then you can directly use:

res = out["rates"]["CZK"]
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

Unknown structure Approach

Assuming you only know the desired key name and nothing else you can follow this approach.

def find_key(data, key_name):
    for k,v in data.items():
        if k==key_name:
            print(k)
            break
        elif isinstance(v, dict):
            find_key(data[k], key_name)
        else:
            continue

This will look in the dictionary for your key, no matter how deep it is placed.

known structure Approach

Checkout this answer

SimpleNamespace and object_hook are of great value.

Gr3at
  • 330
  • 6
  • 12