wikipedia
This commit is contained in:
parent
2df04078b4
commit
7af284a92f
10
wikipedia
10
wikipedia
@ -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)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user