Main Content

JSON from Python - first principles, easy example

Archive - Originally posted on "The Horse's Mouth" - 2013-05-13 18:53:37 - Graham Ellis

Here's a short example of how to pick up a JSON feed from a URL in Python. All the examples I came across looked very complicated, so I thought I would write one that's really straightforward:

Open a remote URL feed that provides a JSON object:

  response = urllib2.urlopen('http://www.wellho.net/services/pix.json')

Read that object in:

  stuff = response.read()

That'll give you a dict... and you can look at the keys:

  for itemname in memory.keys():
    print itemname


... you can get at individual values:

  toby = time.gmtime(memory["timedat"])
  print "This was generated at",memory["timedat"],time.strftime("%c",toby)


  if memory["lookfor"]:
    print "Searching only for",memory["lookfor"]
  else:
    print "All available records requested"


... and you can look deeper into the structure if you like:

  for record in memory["acc"]:
    print record["when"], record["which"]


Full code [here]. More about urllib2, JSON from Pyton and lots of other subjects on our Intermediate Python Course