python: serialize a dictionary into a simple html output

前端 未结 9 649
轮回少年
轮回少年 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:33

    I needed something similar, but also wanted to pretty print lists, and lists inside the dict. Here's what I came up:

    def format(self, obj, indent = 1):
        if isinstance(obj, list):
            htmls = []
            for k in obj:
                htmls.append(self.format(k,indent+1))
    
            return '[<div style="margin-left: %dem">%s</div>]' % (indent, ',<br>'.join(htmls))
    
        if isinstance(obj, dict):
            htmls = []
            for k,v in obj.iteritems():
                htmls.append("<span style='font-style: italic; color: #888'>%s</span>: %s" % (k,self.format(v,indent+1)))
    
            return '{<div style="margin-left: %dem">%s</div>}' % (indent, ',<br>'.join(htmls))
    
        return str(obj)
    

    Then, if you're using webapp on appengine, you can just do the following:

    self.response.out.write(self.format(obj))
    

    This is an example of the output:

    enter image description here

    0 讨论(0)
  • 2021-01-12 01:36

    Here's my simple solution, It can handle any level of nested dictionary.

    import json
    temp_text = {'decision': {'date_time': None, 'decision_type': None},
                 'not_received': {'date_time': '2019-04-15T19:18:43.825766'},
                 'received': {'date_time': None},
                 'rfi': {'date_time': None},
                 'under_review': {'date_time': None}}
    dict_text_for_html = json.dumps(
        temp_text, indent=4
    ).replace(' ', '&nbsp').replace(',\n', ',<br>').replace('\n', '<br>')
    

    html view of python dict

    0 讨论(0)
  • imagine we have this :{name: "a", children:[{name: "b", children: [] },{..},{..}]

    def ConvertDictToUlLi():
        jsonResult = GetSomeRecursiveDict()
    
        def CreateHtml(DictItem, output):
            output = "<li>"+DictItem["name"] if jsonResult.has_key("name") else " "
            if len(DictItem["children"]) > 0:
               output = output + "<ul>"
               for item in DictItem["children"]:
                  output = output + "  "+CreateHtml(item, output)+"  "
               output = output + "</ul>"
          return output+"</li>"
        result = "<ul class='tree'>"+CreateHtml(jsonResult, "")+"</ul>"
    
    return result
    
    0 讨论(0)
提交回复
热议问题