python: serialize a dictionary into a simple html output

前端 未结 9 648
轮回少年
轮回少年 2021-01-12 00:59

using app engine - yes i know all about django templates and other template engines.

Lets say i have a dictionary or a simple object, i dont know its structure and i

相关标签:
9条回答
  • 2021-01-12 01:15

    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.

    0 讨论(0)
  • 2021-01-12 01:17
    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)
    
    0 讨论(0)
  • 2021-01-12 01:20

    You could use pretty print (pprint)

    or if you want to do some further processing of display then you have to run through the dict yourself.

    Be warned that the code is crude and will require numerous refinements. Solution uses recursion too, which is bad, if the recursion depth is higher.

    z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal', 'telephone':{'home':'xxx','offie':'yyy'}}}}
    
    def printItems(dictObj, indent):
        it = dictObj.iteritems()
        for k,v in it:
            if isinstance(v, dict):
                print ' '*indent , k, ':'
                printItems(v, indent+1)
            else:
                print ' '*indent , k, ':', v
    
    printItems(z,0)
    

    Output:

     data :
      address :
       city : anycity
       postal : somepostal
       street : some road
       telephone :
        home : xxx
        offie : yyy
      id : 1
      title : home
    
    0 讨论(0)
  • 2021-01-12 01:25

    Here is my version with support of lists (labels are verbose names of keys in dictionary):

    def render_value(value, labels):
        if isinstance(value, (list, tuple)):
            return render_list(value, labels)
        elif isinstance(value, dict):
            return render_dict(value, labels)
        else:
            return value
    
    
    def render_list(lst, labels):
        items = [
            '<li>%s</li>' % render_value(value, labels)
            for value in lst
        ]
        return '\n'.join(['\n<ul>'] + items + ['</ul>\n'])
    
    
    def render_dict(dct, labels):
        items = []
        for key, value in dct.items():
            if not value: continue
    
            key = labels.get(key, key)
            value = render_value(value, labels)
            items.append('<li><b>%s</b>: %s</li>' % (key, value))
    
        return '\n'.join(['\n<ul>'] + items + ['</ul>\n'])
    
    0 讨论(0)
  • 2021-01-12 01:28

    None of the above examples give good results, so I wrote two of my own functions that create beautiful looking html output for dictionaries.

    def dict_to_html(dd, level=0):
        """
        Convert dict to html using basic html tags
        """
        import simplejson
        text = ''
        for k, v in dd.iteritems():
            text += '<br>' + '&nbsp;'*(4*level) + '<b>%s</b>: %s' % (k, dict_to_html(v, level+1) if isinstance(v, dict) else (simplejson.dumps(v) if isinstance(v, list) else v))
        return text
    
    def dict_to_html_ul(dd, level=0):
        """
        Convert dict to html using ul/li tags
        """
        import simplejson
        text = '<ul>'
        for k, v in dd.iteritems():
            text += '<li><b>%s</b>: %s</li>' % (k, dict_to_html_ul(v, level+1) if isinstance(v, dict) else (simplejson.dumps(v) if isinstance(v, list) else v))
        text += '</ul>'
        return text
    
    0 讨论(0)
  • 2021-01-12 01:30

    Look at my implementation:

    def pretty_items(r, d, nametag="<strong>%s: </strong>", itemtag='<li>%s</li>',
                 valuetag="%s", blocktag=('<ul>', '</ul>')):
    if isinstance(d, dict):
        r.append(blocktag[0])
        for k, v in d.iteritems():
            name = nametag % k
            if isinstance(v, dict) or isinstance(v, list):
                r.append(itemtag % name)
                pretty_items(r, v)
            else:
                value = valuetag % v
                r.append(itemtag % (name + value))
        r.append(blocktag[1])
    elif isinstance(d, list):
        r.append(blocktag[0])
        for i in d:
            if isinstance(i, dict) or isinstance(i, list):
                r.append(itemtag % " - ")
                pretty_items(r, i)
            else:
                r.append(itemtag % i)
        r.append(blocktag[1])
    

    Will output all items in HTML format using <ul> and <li> tags. And is also optional to change the tags. And then, just use CSS to handle with the indentation.

    0 讨论(0)
提交回复
热议问题