Pretty print JSON in python

Snippet
import json

Use json.dumps and

...
 
def import_json_files(directory):
    json_files = []
    try:
        for filename in os.listdir(directory):
            if filename.endswith(".json"):
                print(f"Processing {filename}")
                if os.path.getsize(os.path.join(directory, filename)) > 0:
                    with open(os.path.join(directory, filename), 'r') as file:
                        data = json.load(file)
                        #
                        #
                        # Convert the JSON to a string, adjusting the indentation on output
                        #
                        #
                        json_str = json.dumps(data[0], indent=4)
                        print(json_str)
                        #
                        #
                        #
                        json_files.append(data)
                else:
                    print(f" ** empty file!")
        return json_files
    except FileNotFoundError:
        print(f"Directory {directory} not found.")
        return None
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None
 
...

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.