python code - json dump
A sample code, to walk through to understand the "os.walk" method to traverse through the directory and sub-directories and looking for json files only and dumping the data of the json file.
A example of the directory structure:
In the above example, I have created a simple directory structure, where I we have a few json files.
The first step:
The use of "os.walk" method. This method return the "root" directory, the "sub-directories" and the files.
领英推荐
In the above screen-shot you can see all the files and directory details, from down-to-top order.
In this part, we are looking for "json" files within the root and sub-directories.
Now a simple approach to dump the "json" files data:
import os
import json
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
# printing file name if its a .json file.
if name.endswith(".json"):
print("\nprinting json files")
print(os.path.join(root, name))
# parshing json files.
full_path = os.path.join(root, name)
try:
with open(full_path, 'r') as f:
data = json.load(f)
print(f"File: {full_path}")
print(json.dumps(data, indent=4)) # Pretty print JSON content
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Error processing {full_path}: {e}")
This is a sample code, where its traversing through current directory and dumping the data of json files with in the current directory.
Note: This is just a simple code, you can update the code, to understand this simple approach. You can level-up based on your need. Example: taking the complete path of the directory as an argument.