python: serialize a dictionary into a simple html output

前端 未结 9 768
轮回少年
轮回少年 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 '[
    %s
    ]' % (indent, ',
    '.join(htmls)) if isinstance(obj, dict): htmls = [] for k,v in obj.iteritems(): htmls.append("%s: %s" % (k,self.format(v,indent+1))) return '{
    %s
    }' % (indent, ',
    '.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

提交回复
热议问题