For loop for different size of json files

82 Views Asked by At

Let’s say I have multiple json files like: Example1:

{
    "a": "1",
    "b": "2",
    "c": "3",
    "d": "4",
}

Example2:

{
    "a": "1",
    "b": "2",
    "c": "3"
}

Example 3:

{
    "a": "1",
    "b": "2",
    "c": "3",
    "d": "4",
    "e": "5"

}

etc. I want to iterate these files for example with for loop and print out them into a file based on their elements like:

a 1
b 2
c 3

or

a 1
b 2
c 3
d 4
e 5

My json files are too big and I want to automate this. What would be the easiest way?

1

There are 1 best solutions below

0
gkuegler On

Maybe try something along these lines.

import json
    
filenames = [
    "file1.json",
    "file2.json",
    "file3.json",
]
    
for name in filenames:
    with open(name, "r") as f:
        data = json.load(f)
        for key in data.keys():
            print(f"{key}: {data[key]}")