user9692945
user9692945

Reputation: 39

Handling nested JSON in Python

I'm attempting to retrieve data from within a nested JSON data using Python.

Abbreviated example of the JSON data:

{

    "daily" : {
        "1524182400000" : 438,
        "1524268800000" : 438,
        "1524355200000" : 437,
        "1524441600000" : 437,
        "1524528000000" : 432
    }
}

As you see, each of the above keys is a unix timestamp and the overall object is constantly updated with new key/value pairs.

While I am easily able to retrieve the data if I know the timestamp I don't know how I get the value of the latest timestamp.

I would usually complete this in PHP with the below code and selecting the array position:

foreach ($data["daily"] as $timedate => $value) {
    array_push($ValueArray, $value);
    array_push($ValueDate, $timedate);
}

How do I get this in Python?

Any help would be appreciated!

Upvotes: 3

Views: 182

Answers (3)

Lemayzeur
Lemayzeur

Reputation: 8525

For what you are loking for, this will work:

json_data['daily'][sorted(json_data['daily'].keys())[-1]]

Upvotes: 0

wbadart
wbadart

Reputation: 2911

The entry you're looking for is prices['daily'][max(prices['daily'], key=int)].

max(prices['daily'], key=int) iterates over the keys and find the largest (aka, most recent) one. Setting key=int ensures the function does a numerical, rather than lexical comparison.

Upvotes: 4

Adriano Martins
Adriano Martins

Reputation: 1808

just use the equivalent of foreach in python:

for timedate, value in tmp['daily'].items():
    # Do something with timedate or value...

It works exactly like the foreach on php.

Upvotes: 0

Related Questions