title: Extract values from JSON in Python
body: <p>This is a reply from the Google Distance Matrix. I would like to have only the two value's as an output and I'm trying to extract it with Python. </p>
  
  <pre><code>{
     "destination_addresses" : [ "Hoorn, Nederland" ],
     "origin_addresses" : [ "Amsterdam, Nederland" ],
     "rows" : [
        {
           "elements" : [
              {
                 "distance" : {
                    "text" : "45,0 km",
                    "value" : 44952
                 },
                 "duration" : {
                    "text" : "40 min.",
                    "value" : 2423
                 },
                 "status" : "OK"
              }
           ]
        }
     ],
     "status" : "OK"
  }
  </code></pre>
  
  <p>This is what I've tried so far. I want to have a reply from Google every 15 minutes and write it to a file. But in the file I only want the value for distance and duration and I have no luck in achieving that. I'm not sure if the reply from Google is proper JSON so I've tried json.loads but it did not allow me to extract certain parts from the reply. Any ideas?</p>
  
  <pre><code>import requests
  import json
  import datetime
  from apscheduler.schedulers.blocking import BlockingScheduler
  
  uri = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=Amsterdam&amp;destinations=Hoorn&amp;mode=driving&amp;key="
  now = datetime.datetime.now()
  
  def job():
      datum = now.strftime("%Y-%m-%d %H:%M")
      print datum
      text_file = open('tijdsduur.txt', 'a')
      batch = requests.get(uri)
      data = batch.text
      jdata = json.loads(data)
      print jdata['elements']['distance']['value']
      text_file.write(data)
      text_file.write('\n')
      text_file.close()
  
  job()
  scheduler = BlockingScheduler()
  scheduler.add_job(job, 'interval', minutes=15)
  scheduler.start()
  </code></pre>
  
  <p>Error when I try json.loads: KeyError 'elements'</p>