Created
May 3, 2025 22:16
-
-
Save alexanderdombroski/2968d3eb4bf6473bc5035c7e2ae6abe4 to your computer and use it in GitHub Desktop.
Python snippet functions that interact with json in a file or from an API. Each has a prefix beginning with json. | Created using SnippetStudio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
| { | |
| "read json from file": { | |
| "prefix": "json_read", | |
| "body": [ | |
| "def read_json(filename: str) -> any:", | |
| " with open(filename) as file_data:", | |
| " json_data = json.load(file_data)", | |
| " return json_data" | |
| ], | |
| "description": "Reads json from a file using the import json library", | |
| "scope": "python" | |
| }, | |
| "write json to a file": { | |
| "prefix": "json_write", | |
| "body": [ | |
| "def write_json(data: any, filename: str) -> None:", | |
| " with open(filename, 'w') as file:", | |
| " json.dump(data, file, indent=4)" | |
| ], | |
| "description": "Creates a function to write json to a file using the json library", | |
| "scope": "python" | |
| }, | |
| "read json from an api using requests": { | |
| "prefix": "json_read_api", | |
| "body": [ | |
| "def json_read_api(url: str) -> dict:", | |
| " try:", | |
| " response = requests.get(url)", | |
| " response.raise_for_status()", | |
| " return response.json()", | |
| " except requests.exceptions.HTTPError as http_err:", | |
| " raise RuntimeError(f\"HTTP error occurred: {http_err}\") from None", | |
| " except requests.exceptions.RequestException as req_err:", | |
| " raise RuntimeError(f\"Request error occurred: {req_err}\") from None", | |
| " except ValueError as json_err:", | |
| " raise ValueError(f\"JSON decode error: {json_err}\") from None" | |
| ], | |
| "description": "Creates a function to return a json object from an API", | |
| "scope": "python" | |
| }, | |
| "print api data from url": { | |
| "prefix": "json_print_api", | |
| "body": [ | |
| "def display_api_data(url: str) -> None:", | |
| " response = requests.get(url)", | |
| " if response.status_code == 200:", | |
| " data = response.json()", | |
| " print(json.dumps(data, indent=4))", | |
| " else:", | |
| " print(f\"Request failed with status code {response.status_code}\")" | |
| ], | |
| "description": "gets json data using requests, parses with json, then prints", | |
| "scope": "python" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment