Summary

I once promised to wirte a tut on how to use functions etc in Python. Here it is.

I’m gonna read a JSON file, with this tutorial, so find yourself a nice JSON document and follow my trail.

Pre-coding

Normally, before actually coding, we need pip to install requirements for our script. In your terminal:

#osx
sudo easy_install pip

#linux
sudo apt-get install python-pip

In terminal, pip install -r requirements.txt. But in this case we don’t need to as we don’t import anything special.

Start Actual Coding

create a new file, called something like jsonReader.py, As we need to read JSON we need to import the python json lib. Start your file with the following lines of code:

import json

Next up, create a function(!) that will read the JSON file and add some “start-up” text and a call to this function.

def readJson():
	with open('keys.json') as data_file:    
		data = json.load(data_file)
		print(data)
    	

print "start script"
readJson();

 

A little explanation:

  1. def readJson(): is the function call. It def(ines) the function readJson just like how it works in PHP, Javascript and a whole lot more languages.
  2. with open(“keys.json”) as data_file opens the file keys.json and puts it in the data_file variable.
  3. data = json.load(data_file) tells our code to actually load the json information from the previously opened file and store it in the data variable.
  4. print(data) the easy one, it prints the contents of our keys.json to the console.
  5. print “start script” prints exactly that string to your console the moment we start the script.
  6. readJson() actually triggers the defined function to do its magic.

Note, mind the tabbing of the code within the function, Python works on indenting and unindenting blocks.

Execute

Go to your console and type

python jsonReader.py

It should execute now.

Let’s continue,

printing to the console is nice, but not that useful.

Create a new function called processJson. Let this function call upon the readJson function and put the output from this function into a variable called data. Don’t forget to remove the print in the readJson function and return the data.

Try before you copy paste,

import json

def readJson():
	with open('keys.json') as data_file:    
		data = json.load(data_file)
		return data
    	
def processJson():
	data = readJson()
	print data;

print "start script"

processJson()

For now thats a short introduction on functions.