Formatting json cleanly - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Formatting json cleanly (/thread-31054.html) |
Formatting json cleanly - Daring_T - Nov-19-2020 Daring_T here, I have a dictionary that appends to a json file, and it outputs on one line. Is there a way to cleanly format the json data like pprint. This is the original json data Here the code I have to add dicts to the json file.import os import pprint from datetime import datetime def output_board_layout(input_file="battleship.json", add_to_key="_in_book"): """ :parameter input_file inputs json_data to file default is battleship.json add_to_key adds a string to the key :return: dict formatted to json """ battleship_grid = { "a": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "b": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "c": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "d": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "e": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "g": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "h": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "i": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "j": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} dt = datetime.today() key = f"{str(dt.month)}-{str(dt.day)}-{str(dt.year)[2:]}_{str(dt.hour)}:{str(dt.minute)}.{str(dt.second)}" key = key + add_to_key new_battleship_grid = dict() new_battleship_grid[key] = battleship_grid if os.stat(input_file).st_size != 0: # Checks if file is not empty with open(input_file, "r") as f: existing_json_data = json.load(f) existing_json_data.update(new_battleship_grid) print("\n" * 3) pprint.pprint(existing_json_data) json_file_data = json.dumps(existing_json_data) else: json_file_data = json.dumps(new_battleship_grid) with open(input_file, "w") as f: # json.dump(json_file_data, f) f.write(json_file_data) return json_file_dataThanks For reading, Daring_T |