vivtsai commited on
Commit
b78e234
·
1 Parent(s): 53cf224

Add script to produce Markdown input for Data Cards Labs

Browse files

This script will only work with JSON files produced by `reformat_json.py`.

Files changed (1) hide show
  1. formatting/json_to_md.py +72 -0
formatting/json_to_md.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser
2
+ from json import load
3
+
4
+ def parse_args():
5
+ parser = ArgumentParser()
6
+ parser.add_argument('input', type=str, nargs='+', \
7
+ help='Specify paths to files (e.g., path/to/*.json)')
8
+
9
+ return parser.parse_args()
10
+
11
+
12
+ def json_to_markdown(filename):
13
+ json = load(open(filename))
14
+
15
+ markdown = f'# {json["name"]}\n\n'
16
+ markdown += json['summary'] + '\n\n'
17
+
18
+ for key in json:
19
+ if key not in ('name', 'summary', 'sections'):
20
+ markdown += f'#### {key}\n{json[key]}\n\n'
21
+
22
+ markdown += '\n'.join(section_to_markdown(section) \
23
+ for section in json['sections'])
24
+
25
+ with open(f'{filename[:-5]}.md', 'w') as f:
26
+ f.write(markdown)
27
+
28
+
29
+ def section_to_markdown(section):
30
+ markdown = f'{"#" * section["level"]} {section["title"]}\n\n'
31
+ markdown += '\n'.join(subsection_to_markdown(subsection) \
32
+ for subsection in section['subsections'])
33
+
34
+ return markdown + '\n'
35
+
36
+
37
+ def subsection_to_markdown(subsection):
38
+ markdown = f'{"#" * subsection["level"]} {subsection["title"]}\n\n'
39
+ markdown += '\n'.join(field_to_markdown(field) \
40
+ for field in subsection['fields'])
41
+
42
+ return markdown + '\n'
43
+
44
+
45
+ def field_to_markdown(field):
46
+ markdown = f'{"#" * field["level"]} {field["title"]}\n\n'
47
+
48
+ if 'flags' in field and 'quick' in field['flags']:
49
+ markdown += f'<!-- quick -->\n'
50
+
51
+ if field.get('info', False):
52
+ markdown += f'<!-- info: {field["info"]} -->\n'
53
+
54
+ if field.get('scope', False):
55
+ markdown += f'<!-- scope: {field["scope"]} -->\n'
56
+
57
+ markdown += field.get('content', '')
58
+
59
+ return markdown + '\n'
60
+
61
+
62
+ def main():
63
+ """Converts JSON files from `reformat_json.py`
64
+ to Markdown input for Data Cards Labs."""
65
+ args = parse_args()
66
+ for filename in args.input:
67
+ if filename[-5:] == '.json':
68
+ json_to_markdown(filename)
69
+
70
+
71
+ if __name__ == '__main__':
72
+ main()