Example program that retrieves a remote JSON file/URL, and outputs the JSON response to the console.
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import json
from urllib import urlopen
import argparse
def usage(prog):
print('')
print('Gets a JSON URL.')
print('Download the json file from the url and returns a decoded object.')
print('')
print('Usage:')
print('')
print(' %s <url>' % prog)
print('')
def get_json(json_url):
f = urlopen(json_url)
data = f.read().decode('utf-8')
f.close()
return json.loads(data)
if __name__ == '__main__':
progname = os.path.basename(str(sys.argv[0]))
args = sys.argv[1:]
if not args or len(args) < 1:
usage(progname)
sys.exit(2)
arg = sys.argv[1]
status = 0
for url in args:
if not url:
status = 1
print(progname + ':', url + ':', 'empty url')
else:
print(str(get_json(url)))
sys.exit(status)