22
33"""
44Reads a JSON file, sorts its top-level keys numerically,
5- and writes the sorted data to a new JSON file following Prettier style.
6-
7- Prettier config: printWidth=150, tabWidth=2, useTabs=false, trailingComma=es5, bracketSpacing=false
5+ and writes the sorted data to a new JSON file.
6+ Prettier will format the output according to .prettierrc config.
87
98python scripts/normalize_json.py data/leetcode-problems.json
109"""
1514from collections import OrderedDict
1615
1716
18- def format_json_value (value , indent_level = 0 , print_width = 150 ):
19- """Format a JSON value with custom formatting following Prettier style."""
20- indent = " " * indent_level
21- next_indent = " " * (indent_level + 1 )
22-
23- if isinstance (value , dict ):
24- if not value :
25- return "{}"
26- items = []
27- for k , v in sorted (value .items ()):
28- formatted_key = json .dumps (k , ensure_ascii = False )
29- formatted_value = format_json_value (v , indent_level + 1 , print_width )
30- items .append (f"{ next_indent } { formatted_key } : { formatted_value } " )
31- return "{\n " + ",\n " .join (items ) + "\n " + indent + "}"
32- elif isinstance (value , list ):
33- if not value :
34- return "[]"
35- # Check if it's a list of numbers (for problems arrays) - format multiple per line
36- if value and isinstance (value [0 ], (int , float )):
37- # Calculate available width (print_width minus indentation and brackets)
38- available_width = print_width - len (next_indent ) - 2
39- lines = []
40- current_line = []
41- current_length = 0
42-
43- for i , item in enumerate (value ):
44- item_str = str (item )
45- # Add comma and space length (2) if not first item on line
46- item_length = len (item_str ) + (2 if current_line else 0 )
47-
48- if current_length + item_length > available_width and current_line :
49- # Start a new line
50- lines .append (", " .join (str (x ) for x in current_line ))
51- current_line = [item ]
52- current_length = len (item_str )
53- else :
54- current_line .append (item )
55- current_length += item_length
56-
57- if current_line :
58- lines .append (", " .join (str (x ) for x in current_line ))
59-
60- # Format with proper indentation
61- formatted_lines = [f"{ next_indent } { line } " for line in lines ]
62- return "[\n " + ",\n " .join (formatted_lines ) + "\n " + indent + "]"
63- else :
64- # Format other arrays - check if they fit on one line
65- formatted_items = [format_json_value (item , indent_level + 1 , print_width ) for item in value ]
66- total_length = sum (len (str (item )) for item in formatted_items )
67- if total_length < 100 and len (value ) <= 5 :
68- # Short arrays on one line
69- return "[" + ", " .join (str (item ).replace ("\n " , " " ) for item in formatted_items ) + "]"
70- else :
71- # Long arrays with line breaks
72- items = [f"{ next_indent } { item } " for item in formatted_items ]
73- return "[\n " + ",\n " .join (items ) + "\n " + indent + "]"
74- else :
75- return json .dumps (value , ensure_ascii = False )
76-
77-
7817def sort_json_by_numeric_keys (input_file , output_file ):
7918 """
8019 Sort JSON file by numeric keys and format according to Prettier style.
@@ -94,18 +33,9 @@ def sort_json_by_numeric_keys(input_file, output_file):
9433 sorted_items = sorted (data .items (), key = lambda item : int (item [0 ]))
9534 sorted_data = OrderedDict (sorted_items )
9635
97- # Format the JSON with custom formatting following Prettier style
98- lines = ["{" ]
99- items = []
100- for key , value in sorted_data .items ():
101- formatted_key = json .dumps (key , ensure_ascii = False )
102- formatted_value = format_json_value (value , 1 , print_width = 150 )
103- items .append (f' { formatted_key } : { formatted_value } ' )
104- lines .append (",\n " .join (items ))
105- lines .append ("}" )
106-
36+ # Write JSON (Prettier will format it)
10737 with open (output_file , "w" , encoding = "utf-8" ) as f :
108- f . write ( " \n " . join ( lines ) + " \n " )
38+ json . dump ( sorted_data , f , ensure_ascii = False )
10939
11040 # Format with prettier
11141 try :
0 commit comments