Last active
December 31, 2020 11:15
-
-
Save LouisdeBruijn/6946c9341b2da7307519c44ef10b0fc8 to your computer and use it in GitHub Desktop.
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
| import os | |
| import json | |
| from datetime import datetime | |
| from logging import info | |
| def json_to_file(file_loc=False, json_data=None, create_indexes=False, unescape_html=False): | |
| """Create JSON file object. | |
| :param file_loc: location of file to write to | |
| :type file_loc: str, bool | |
| :param json_data: data to write | |
| :type json_data: dict, list | |
| :param create_indexes: whether to create indexes in the values | |
| :type create_indexes: bool | |
| :param unescape_html: whether to escape html entities such as & and >e; | |
| :type unescape_html: bool | |
| """ | |
| if create_indexes: | |
| for idx, element in enumerate(json_data): | |
| element['id'] = element.get('id', idx) | |
| if file_loc: | |
| now = datetime.now() | |
| date_time = now.strftime("_%m-%d-%Y_%H-%M-%S") | |
| file, extension = os.path.splitext(file_loc) | |
| file_loc = file + date_time + extension | |
| if unescape_html: | |
| json_data = unescape_html_wrapper(json_data) | |
| with open(file_loc, "w") as outf: | |
| json.dump(json_data, outf, allow_nan=False, default=str, indent=2) | |
| info("Saved output in file: '{0}'.".format(os.path.join(os.path.abspath(os.getcwd()), file_loc))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment