skip to Main Content

I have multiple JSON files in a folder (~200) which I would like to combine and generate a single JSON file. I am trying following lines of code.

result = ''
for f in glob.glob("*.json"):
    with open(f, "r", encoding='utf-8') as infile:
        result += infile.read()
        
with open("merged_file.json", "w", encoding='utf-8') as outfile:
    outfile.writelines(result)

However, it generate the file with JSON content but all the content is in only one line. How can I append the content as it is in the files.

3

Answers


  1. Maybe this :

    import json
    import glob
    
    all_config = {}
    
    for f in glob.glob("*.json"):
        with open(f, "r", encoding='utf-8') as infile:
            json_content = json.load(infile)
            all_config.update(json_content)
            
            
    with open("All.json", "w+") as outfile:
        outfile.write(str(json.dumps(all_config, indent=4)))
    
    Login or Signup to reply.
  2. You do it by reading and parsing each JSON file, appending the parsed content to a list,

    Example below:

    json_objects = []
    
    for f in glob.glob("*.json"):
        try:
            with open(f, "r", encoding='utf-8') as infile:
                file_content = json.load(infile)
                json_objects.append(file_content)
        except json.JSONDecodeError as e:
            print(f"Error {f}: {e}")
    
    with open("merged_file.json", "w", encoding='utf-8') as outfile:
        json.dump(json_objects, outfile, ensure_ascii=False, indent=4)
    
    Login or Signup to reply.
  3. hi run it and when done you can edit ALL_DATA._json -> ALL_DATA.json

    import json
    import glob
    
    all_data = {}
    
    for f in glob.glob("*.json"):
    with open(f, "r", encoding='utf-8') as infile:
        json_content = json.loads(infile.read())
        all_data.update(json_content)
        
        
    with open("All_DATA._json", "w+") as outfile:
        outfile.write(str(json.dumps(all_data, indent=4)))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search