json2html.html
001| '''JSON-to-HTML. Use a JSON file to define an HTML page.
001|
001| In retrospect, this was kind of a dumb idea.
001|
001| Functions:
001| json_to_html (source:dict) ~convert a dict to HTML
001| generate_html (html, node) ~recursive HTML generator
001| save_json (fname, fpath) ~write JsonHtml to a JSON file
001|
001| Data:
001| JsonHtml ~demo JSON for defining an HTML page
001|
001| Commands:
001| main do_main ~convert a JSON file to HTML
001| demo do_demo ~convert a JSON file to HTML (demo)
001| save do_save_json ~save demo JSON to a JSON file
001| test do_test ~test
001|
001| '''
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date, datetime
007| from json import dump as jsonsave
008| from logger import logger,info,debug,trace, LogFilenameTimestamp
009| from goodies import KWARG
010| from files import linefile, jsonfile
011| from webpage import WebPage
012|
013| BasePath = r'C:\CJS\prj\Python\app\tmake'
014| HtmlPath = r'C:\CJS\www\root\tmp'
015| Log = logger('json2html')
016|
017| CMND = ''
018| ARGS = {
019|
020| 'jpath': BasePath,
021|
022| 'fpath': BasePath,
023| }
024|
025|
026| CharName = '_'
027| CharText = '$'
028| CharAttr = '@'
029|
030|
031| JsonHtml = {
032| 'version': 1,
033| 'meta': {
034| 'charset': 'UTF-8',
035| 'html': 4,
036| },
037| 'head': {
038| CharName: 'JSON Test File',
039| 'Content-Type': 'text/html; charset=UTF-8',
040| 'Date-Created': datetime(2024,1,15,7,14,51).ctime(),
041| 'Last-Modified': datetime(2024,3,28,9,22,52).ctime(),
042| 'keywords': ['big', 'bad', 'wolf', 'red', 'hood'],
043| 'X-Clacks-Overhead':'Sir Terry Pratchett',
044| },
045| 'body': [
046| {
047| CharName:'div',
048| '@class':'PageHead',
049| '@style':'background-color:#efefef;padding:0;',
050| CharText:[
051| {CharName:'h1', CharText:'Logos con Carne'},
052| {CharName:'h2', CharText:'JSON Test File'},
053| ]
054| },
055| {
056| CharName:'div',
057| '@class':'PageBody',
058| CharText:[
059| {CharName:'h3', CharText:'Hello, World!'},
060| {CharName:'table', CharText: [
061| {CharName:'caption', '@class':'TCaption', CharText:'My Big Table!'},
062| {CharName:'thead', CharText: [
063| {CharName:'tr', CharText: [
064| {CharName:'th', '@class':'TC1', CharText:'#'},
065| {CharName:'th', '@class':'TC2', CharText:'Name'},
066| {CharName:'th', '@class':'TC3', CharText:'Type'},
067| {CharName:'th', '@class':'TC4', CharText:'Note'},
068| ]},
069| ]},
070| {CharName:'tbody', CharText: [
071| {CharName:'tr', CharText: [
072| {CharName:'th', '@class':'TC1', CharText:'1'},
073| {CharName:'td', '@class':'TC2', CharText:'Science Fiction'},
074| {CharName:'td', '@class':'TC3', CharText:'Books'},
075| {CharName:'td', '@class':'TC4'},
076| ]},
077| {CharName:'tr', CharText: [
078| {CharName:'th', '@class':'TC1', CharText:'2'},
079| {CharName:'td', '@class':'TC2', CharText:'Murder Mystery'},
080| {CharName:'td', '@class':'TC3', CharText:'Books'},
081| {CharName:'td', '@class':'TC4', CharText:'and Detective Stories'},
082| ]},
083| ]}
084| ]}
085| ]
086| },
087| {
088| CharName:'div',
089| '@class':'PageTail',
090| '@width':'250',
091| CharText:[
092| {CharName:'div', '@class':'left' , CharText:'all rights reserved'},
093| {CharName:'div', '@class':'right', CharText:'(c) CJSonnack'},
094| ]
095| },
096| ],
097| 'tail': {
098| 'access':'public',
099| 'archive':'default',
100| 'issue-date': datetime(2024,4,1, 6,0,0).ctime(),
101| 'filename': 'json.html',
102| 'filepath': r'C:\CJS\prj\Python\ws'
103| },
104| 'eof': {}
105| }
106|
107|
108| def save_json (fname='json2html.json', fpath=BasePath):
109| '''Save JsonHtml to a JSON file.'''
110| fn = path.join(fpath, fname) if fpath else fname
111| fp = open(fn, mode='w', encoding='utf-8')
112| try:
113| jsonsave(JsonHtml, fp, indent=3)
114| except:
115| raise
116| finally:
117| fp.close()
118| Log.info(f'wrote: {fn}')
119| print(f'wrote: {fn}')
120|
121|
122|
123| def generate_html (html:list, node:dict):
124| '''Recursive HTML generator.'''
125| name = node[CharName]
126| content = node[CharText] if CharText in node else ''
127|
128|
129| attrs = []
130| for nm in node:
131| if nm.startswith(CharAttr):
132| attr_name = nm[1:]
133| attr_valu = node[nm]
134| attrs.append(f' {attr_name}="{attr_valu}"')
135| extra = ''.join(attrs)
136|
137|
138| if isinstance(content, str):
139| html.append(f'<{name}{extra}>{content}</{name}>')
140|
141| elif isinstance(content, list):
142| html.append(f'<{name}{extra}>')
143| for elem in content:
144|
145| generate_html(html, elem)
146| html.append(f'</{name}>')
147|
148| else:
149| raise RuntimeError('Unexpected content: "{content!s}"')
150|
151|
152| def json_to_html (source:dict=JsonHtml):
153| '''Convert a specially created dict to HTML.'''
154| html = ['<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">']
155| html.append('<html>')
156|
157|
158| head = source['head']
159| title = head[CharName]
160| html.append('<head>')
161| for nam in head:
162| if nam.startswith(CharName):
163| continue
164| val = head[nam]
165| if isinstance(val, list):
166| val = ','.join(val)
167| html.append(f'<meta http-equiv="{nam}" content="{val}">')
168| html.append(f'<title>{title}</title>')
169| html.append('<link rel="stylesheet" type="text/css" href="/basic.css">')
170| html.append('</head>')
171|
172|
173| body = source['body']
174| html.append('<body>')
175| html.append('')
176| for elem in body:
177| generate_html(html, elem)
178| html.append('')
179| html.append('</body>')
180| html.append('</html>')
181| html.append('')
182|
183|
184|
185|
186| return html
187|
188|
189| def do_main (**kwargs):
190| """CMND: Do the thing."""
191| fpath = KWARG('fpath', BasePath, str, kwargs)
192| fname = KWARG('fname', 'json2html.html', str, kwargs)
193| jpath = KWARG('jpath', BasePath, str, kwargs)
194| jname = KWARG('jname', 'json2html.json', str, kwargs)
195| Log.info('main:: %s' % str(list(kwargs.keys())))
196| Log.debug(f'{fpath=}')
197| Log.debug(f'{fname=}')
198| Log.debug(f'{jpath=}')
199| Log.debug(f'{jname=}')
200| Log.info()
201| htmlfilename = path.join(fpath, fname) if fpath else fname
202| jsonfilename = path.join(jpath, jname) if jpath else jname
203|
204|
205| fi = jsonfile(jsonfilename)
206| fi.load()
207|
208|
209| fo = linefile(htmlfilename)
210| fo.data = json_to_html(fi.data)
211| fo.save()
212|
213|
214| Log.info()
215| return 'Done'
216|
217|
218| def do_demo (**kwargs):
219| """CMND: Do the demo."""
220| fpath = KWARG('fpath', BasePath, str, kwargs)
221| fname = KWARG('fname', 'json2html_demo.html', str, kwargs)
222| Log.info('demo:: %s' % str(list(kwargs.keys())))
223| Log.debug(f'{fpath=}')
224| Log.debug(f'{fname=}')
225| Log.info()
226| htmlfilename = path.join(fpath, fname) if fpath else fname
227|
228|
229| fo = linefile(htmlfilename)
230|
231| fo.data = json_to_html()
232|
233| fo.save()
234|
235| print()
236| print('\n'.join(fo.data))
237| print()
238|
239|
240| Log.info()
241| return 'Done'
242|
243|
244| def do_save_json (**kwargs):
245| """CMND: Save JsonHtml to a JSON file."""
246| jpath = KWARG('jpath', BasePath, str, kwargs)
247| jname = KWARG('jname', 'json2html.json', str, kwargs)
248| Log.info('save:: %s' % str(list(kwargs.keys())))
249| Log.debug(f'{jpath=}')
250| Log.debug(f'{jname=}')
251| Log.info()
252| jsonfilename = path.join(jpath, jname) if jpath else jname
253|
254|
255| save_json(fname=jname, fpath=jpath)
256|
257|
258| Log.info()
259| return 'Done'
260|
261|
262| def do_test (**kwargs):
263| """CMND: Do a test."""
264| fpath = KWARG('fpath', BasePath, str, kwargs)
265| fname = KWARG('fname', 'json2html_test.html', str, kwargs)
266| jpath = KWARG('jpath', BasePath, str, kwargs)
267| jname = KWARG('jname', 'json2html.json', str, kwargs)
268| Log.info('test:: %s' % str(list(kwargs.keys())))
269| Log.debug(f'{fpath=}')
270| Log.debug(f'{fname=}')
271| Log.debug(f'{jpath=}')
272| Log.debug(f'{jname=}')
273| Log.info()
274| htmlfilename = path.join(fpath, fname) if fpath else fname
275| jsonfilename = path.join(jpath, jname) if jpath else jname
276|
277|
278| Log.info()
279| return 'Done'
280|
281| def dispatch (cmd, **kwargs):
282| """Dispatch to a module function based on CMD."""
283| Log.info(f'CMD: {cmd}')
284| for kw in kwargs:
285| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
286| Log.info()
287| if cmd == 'main': return do_main(**kwargs)
288| if cmd == 'demo': return do_demo(**kwargs)
289| if cmd == 'save': return do_save_json(**kwargs)
290| if cmd == 'test': return do_test(**kwargs)
291| return 'Nothing to do!'
292|
293| if __name__ == '__main__':
294| print(f'autorun: {argv[0]}')
295| Log.start(path.join(BasePath,'json2html.log'))
296| Log.level(trace())
297| Log.info(argv[0])
298| Log.info()
299| cmd = argv[1] if 1 < len(argv) else CMND
300| kwargs = ARGS
301| for a in argv[2:]:
302| nv = a.split('=', 1)
303| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
304| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
305| try:
306| print(f'CMD: {cmd}')
307| print()
308| obj = dispatch(cmd, **kwargs)
309| print()
310| print(obj)
311| Log.info()
312| Log.info(obj)
313| except:
314| etype, evalue, tb = exc_info()
315| ts = extract_tb(tb)
316| Log.error()
317| Log.error(f'{etype.__name__}: {evalue!s}')
318| Log.error()
319| for t in ts[-5:]:
320| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
321| Log.error(f' {t[3]}')
322| Log.error()
323| raise
324| finally:
325| Log.end()
326|
327| '''eof'''
328|