Baobab Baobab - 2 months ago 7
JSON Question

conditionally parsing json

I am trying to extract a value from a json array using python. How do I get the value for

"energy"
on a specific day? Here is what the json looks like:

{
"emeter": {
"get_daystat": {
"day_list": [
{ "year": 2016, "month": 10, "day": 1, "energy": 0.651000 },
{ "year": 2016, "month": 10, "day": 2, "energy": 0.349000 },
{ "year": 2016, "month": 10, "day": 3, "energy": 0.481000 }
],
"err_code": 0
}
}
}


So for example, using:

parsed_json = json.loads(json)


how would I extract the
"energy"
value for
"year":2016, "month":10, "day":2
?

Answer

parsed_json will have a python dict. You can access the day_list array with a simple linear search.

def get_energy_value_by_date(obj, year, month, day):   
    for value in obj['emeter']['get_daystat']['day_list']:
        if value['year'] == year and value['month'] == month and value['day'] == day:
            return value['energy']


energy = get_energy_value_by_date(parsed_json, 2016, 10, 2)