scripts/bin/pyjson.py

29 lines
629 B
Python
Executable file

#!/usr/bin/env python3
# PyJSON v1.0
# Fetches JSON data from the specified url and pretty prints it.
#
# Usage:
# pyjson.py <url>
import sys, json
from urllib.request import urlopen, Request
if len(sys.argv) < 2:
print('Please provide a url')
sys.exit()
url = sys.argv[1]
if not url.startswith('http'):
url = 'https://' + url
with urlopen(Request(url, headers={'accept': 'application/json', 'user-agent': 'PyJSON/1.0'})) as r:
data = r.read().decode()
if r.status not in [200,202]:
print('Received an error when trying to fetch json:', r.status, data)
sys.exit()
print(json.dumps(json.loads(data), indent=4))