python: serialize a dictionary into a simple html output

import pprint


pprint.pprint(yourDict)

Well, no HTML, but similar to your for/print approach.

EDIT: or use:

niceText = pprint.pformat(yourDict)

this will give you the same nice output with all indents, etc. Now you can iterate over lines and format it into HTML:

htmlLines = []
for textLine in pprint.pformat(yourDict).splitlines():
    htmlLines.append('<br/>%s' % textLine) # or something even nicer
htmlText = '\n'.join(htmlLines)

The example made by pyfunc could easily be modified to generate simple nested html lists.

z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

def printItems(dictObj, indent):
    print '  '*indent + '<ul>\n'
    for k,v in dictObj.iteritems():
        if isinstance(v, dict):
            print '  '*indent , '<li>', k, ':', '</li>'
            printItems(v, indent+1)
        else:
            print ' '*indent , '<li>', k, ':', v, '</li>'
    print '  '*indent + '</ul>\n'

printItems(z,0)

Not terribly pretty of course, but somewhere to start maybe. If all you want to do is visualize data, the pprint module really is good enough. You could just use the "pre" tag on the result from pprint and put that on your web page.

the pprint version would look something like this:

import pprint
z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

print '<pre>', pprint.pformat(z), '</pre>'

And the html output look something like this:

{'data': {'address': {'city': 'anycity',
                      'postal': 'somepostal',
                      'street': 'some road'},
          'id': 1,
          'title': 'home'}}

Which isn't that pretty, but it at least shows the data in a more structured way.

Tags:

Python