python code - json dump

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.


sample output


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.

要查看或添加评论,请登录

Amit Mund的更多文章

  • Trick Question 1

    Trick Question 1

    Question: What is the difference between the following two code. vs Answer(s) Few of the best answers from the comment…

  • python code - know your time

    python code - know your time

    Some time, its good know, how much time your code is taking..

  • Ansible Day 2 - Inventory File

    Ansible Day 2 - Inventory File

    In the previous article we went through the "configuration file". In this configuration file, you can look for a…

  • Ansible Day 1 - Configuration File (ansible.cfg)

    Ansible Day 1 - Configuration File (ansible.cfg)

    ansible.cfg If your search string is ansible, then probably you do know what ansible is.

  • Linux Day 1 - Understanding ls -l output part 1

    Linux Day 1 - Understanding ls -l output part 1

    ls probably the first linux command we might be using. In most of the case it get explained in just 1 following line:…

  • Lets Learn

    Lets Learn

    Sharing is the best way of learning. I believe in this, because we have awesome people like you, who will guide me…

    1 条评论

社区洞察

其他会员也浏览了