Skip to content

Commit aa6b695

Browse files
author
Kraig Brockschmidt
committed
Add sorting script
1 parent 74647c5 commit aa6b695

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

sort-redir.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Python 3 script to sort .openpublishing.redirection.json by any of the fields
2+
# Requires a Python 3 installation on your computer, see https://www.python.org/downloads
3+
#
4+
# Usage:
5+
# python sort-redir.py <options>
6+
#
7+
# Options:
8+
# -i <inputfile> specifies the input file; default is .openpublishing.redirection.json
9+
# -o <outputfile> specifies the output file: default is .openpublishing.redirection.sorted.json
10+
# -s <sortfield> specifies the name of the field to sort by; default is source_path. Can also use redirect_url
11+
12+
import sys
13+
import getopt
14+
import json
15+
16+
def main(argv):
17+
# Arg defaults
18+
in_file = '.openpublishing.redirection.json'
19+
out_file = '.openpublishing.redirection.sorted.json'
20+
sort_field = 'source_path'
21+
usage_string = 'python sort-redir.py [-i <inputfile>] [-o <outputfile>] [-s <sortfield>] [-h] [-?]'
22+
23+
# Process arguments if provided
24+
try:
25+
opts, args = getopt.getopt(argv, "i:o:s:h?") #, ["inputfile=", "outputfile=", "sortfield="]
26+
except getopt.GetoptError:
27+
print(usage_string)
28+
sys.exit(2)
29+
30+
for opt, arg in opts:
31+
if opt == '-h' or opt == '-?':
32+
print(usage_string)
33+
sys.exit()
34+
elif opt in ("-i", "--inputfile"):
35+
in_file = arg
36+
elif opt in ("-o", "--outputfile"):
37+
out_file = arg
38+
elif opt in ("-s", "--sortfield"):
39+
sort_field = arg
40+
41+
print('Sorting', in_file, 'by', sort_field, 'into', out_file)
42+
43+
with open(in_file) as file:
44+
data = json.load(file)
45+
46+
# The redirections object within the json
47+
redirects = data['redirections']
48+
49+
# Do the sorting and stuff the array back into the original json object
50+
data_sorted = sorted(redirects, key = lambda redirect: redirect[sort_field])
51+
data['redirections'] = data_sorted
52+
53+
with open(out_file, 'w') as outfile:
54+
json.dump(data, outfile, indent=4)
55+
56+
57+
if __name__ == "__main__":
58+
# Give main all args except the .py filename
59+
main(sys.argv[1:])

0 commit comments

Comments
 (0)