Filip Sklenicka
Filip Sklenicka

Reputation: 15

how to isolate part of json in python?

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}

Upvotes: 0

Views: 277

Answers (2)

Gr3at
Gr3at

Reputation: 492

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.

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9590

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"]

Upvotes: 1

Related Questions