conditionally parsing json
<p>I am trying to extract a value from a json array using python. How do I get the value for <code>"energy"</code> on a specific day? Here is what the json looks like:</p>

<pre><code>{
  "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
    }
  }
}
</code></pre>

<p>So for example, using:</p>

<pre><code>parsed_json = json.loads(json)
</code></pre>

<p>how would I extract the <code>"energy"</code> value for <code>"year":2016, "month":10, "day":2</code>?</p>

<p><code>parsed_json</code> will have a python dict. You can access the <code>day_list</code> array with a simple linear search.</p>

<pre><code>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)
</code></pre>

python json