Skip to content

Instantly share code, notes, and snippets.

@DuaneR5280
Last active February 15, 2021 16:40
Show Gist options
  • Save DuaneR5280/5be941b7ccbcdefd7274c7e9bd5fcb39 to your computer and use it in GitHub Desktop.
Save DuaneR5280/5be941b7ccbcdefd7274c7e9bd5fcb39 to your computer and use it in GitHub Desktop.
Script to open and sort JSON file by Key "name" value. Save to new JSON file with sorted_ prefix
# Script to sort json file by Key "name" value
import json
from pathlib import Path
def write_json(data, filename):
"""Write new JSON file
Args:
data (dict): Dict data to write to JSON file
"""
with open("sorted_" + filename, 'w') as jfile:
json.dump(data, jfile)
return
def open_json(*filename):
"""Open JSON file and sort by key name value
Args:
filename (Path): pathlib Path file name string
"""
for file in filename:
with open(file, 'r') as jfile:
data = json.load(jfile)
sorted_data = sorted(data, key=lambda k: k["name"])
write_json(sorted_data, file.name)
return
data_folder = Path("YOUR JSON FILES FOLDER")
j_files = [files for files in Path(data_folder).iterdir()
if files.suffix == ".json"
and files.name != 'error log.json']
open_json(*j_files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment