JSON in Python

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search


JSON is plain-text data exchange format, which stores information in key–value pairs, much like in a python dictionary.

JSON can be commonly found in responses from WEB APIs and web-brower extensions can be installed to facillitate reading by humans. For instance the Mediawiki web API response to the following query:


JSON allowed data-types are:

  • Number
  • String
  • Boolean: either of the values true or false
  • Array
  • Object (or dictionary)
  • Null: An empty value, using the word Null

JSON in Python

The most common JSON actions in Python are load and dump will

  • loads: loads a JSON string (often read from a file) into a python dictionary
  • dumps: dumps a Python dictionary onto a JSON string (often to be writen to a file)

More on JSON in Python

import json, urllib2, pprint

# fetch a JSON content using urllib2
url = 'https://pzwiki.wdka.nl/mw-mediadesign/api.php?action=query&titles=Students&prop=revisions&rvprop=content&format=json'
response = urllib2.urlopen(url)
response_str = response.read()
print 'response_str type is:', type(response_json) 

# Loading JSON
response_dict = json.loads(response_str)

print 'response_dict type is:', type(response_dict)
print 'dict keys:', response_dict.keys() # query is only key, but has dictionaries as values. 

# ** How to access the get the value for key: title ??? **

#pprint.pprint(response_dict) #pprint module prodives indentantion when printing dictionaries

# Dumping JSON
piratelibs = {'Memory_or_the_World':'Marcel Mars', 'aaaarg': 'Sea Dockray', 'Monoskop':'Dusan Barok', 'Sci-hub': 'Alexandra Elbakyan'}
print 'piratelibs type:', type(piratelibs)
piratelibs_json = json.dumps(piratelibs) # dump to JSON string
print 'piratelibs_json type:', type(piratelibs_json)
print piratelibs_json

# now that we have the pirate libs in a JSON string we can save it to a file
jsonfile = open('piratelibs.json', 'w') # open file for writing 'w'
jsonfile.write(piratelibs_json) # write content of piratelibs_json var to it
jsonfile.close() # close it
# check the folder where this .py is located; see if piratelibs.json is there and what is its content