|
|
@@ -2,24 +2,28 @@ |
|
|
|
import requests |
|
|
|
import sys |
|
|
|
import textwrap |
|
|
|
try: |
|
|
|
from simplejson.errors import JSONDecodeError |
|
|
|
except ImportError: |
|
|
|
from json.decoder import JSONDecodeError |
|
|
|
|
|
|
|
# Fetch JSON from url and run it through transform, pretty printing errors |
|
|
|
# and the data worked on as exhaustively as possible. |
|
|
|
def json_query(url, transform, params={}): |
|
|
|
try: |
|
|
|
result = requests.get(url, params) |
|
|
|
except ConnectionError: |
|
|
|
except requests.exceptions.ConnectionError: |
|
|
|
print("Network connection error.") |
|
|
|
sys.exit(1) |
|
|
|
try: |
|
|
|
data = result.json() |
|
|
|
except JSONDecodeError as err: |
|
|
|
print('Error when decoding JSON:\nFrom endpoint ' + url + ':\n' + err + '\n' + result + '\n') |
|
|
|
print('Error when decoding JSON:\nFrom endpoint ' + url + ':\n' + str(err) + '\n' + str(result) + '\n') |
|
|
|
sys.exit(1) |
|
|
|
try: |
|
|
|
return transform(data) |
|
|
|
except (IndexError, KeyError) as err: |
|
|
|
print('Error when traversing JSON:\nFrom endpoint ' + url + ':\n' + err) |
|
|
|
print('Error when traversing JSON:\nFrom endpoint ' + url + ':\n' + str(err)) |
|
|
|
pprint.PrettyPrinter(indent=2).pprint(data) |
|
|
|
sys.exit(1) |
|
|
|
|
|
|
|