Peter Toth
Peter Toth

Reputation: 770

How can I get attribute of attribute in python from json?

I encountered a simple problem while learning python and I can't find the answer to it.

Say we have a json:

{
"Meta Data": {
   "random": "random"
},
"Time Series (1min)": {
    "2020-03-31 16:00:00": {
        "1. open": "523.1900",
        "2. high": "524.9000",
        "3. low": "523.1000",
        "4. close": "524.5200",
        "5. volume": "138425"
    },
    "2020-03-31 15:59:00": {
        "1. open": "522.0100",
        "2. high": "523.8900",
        "3. low": "522.0100",
        "4. close": "523.4100",
        "5. volume": "82971"
    }
 }
 }

Now I want to get all of the "close" attributes from this json as a list of strings, how can I do this using python 3.7 ?

Upvotes: 0

Views: 1908

Answers (2)

Emerson
Emerson

Reputation: 1166

1) extract the dict that you need to get data from 2) loop through the dict, get the key that ends with ‘close’ and then just retrieve the value for that key. You can do the whole thing in 1 line 3) the output is a list of close values

data=json.loads(jsondata)
tm_data = data['Time Series (1min)']
close_items = [value[internalvalue] for key,value in tm_data.items() for internalvalue in value.keys() if internalvalue.endswith('close')]

Upvotes: 1

Pygirl
Pygirl

Reputation: 13349

I assume you want to use close attributes value.

Modified brunns's code:

def get_value(d, k):
    keys_value = []
    if k in d.keys():
        return d[k]
    for key, value in d.items():
        if isinstance(value, dict):
            item = get_value(value, k)
            if item:
#                 print(item)
                keys_value.append(item)
    return keys_value

vals = get_value(js, '4. close')[0]
vals

Output:

['524.5200', '523.4100']

Here js is your input JSON.

Upvotes: 1

Related Questions