使用app引擎 - 是的我知道所有关于django模板和其他模板引擎.
让我说我有一个字典或一个简单的对象,我不知道它的结构,我想将其序列化为HTML.
所以,如果我有
{'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}
Run Code Online (Sandbox Code Playgroud)
我想要的是使用列表或表格以某种形式呈现的可读html;
data:
id:1
title:home
address:
street: some road
city: anycity
postal:somepostal
Run Code Online (Sandbox Code Playgroud)
现在我知道我能做到
for key in dict.items
print dict[key]
Run Code Online (Sandbox Code Playgroud)
但是,当键/值是字典时 - 即地址字典,它不会深入到子值并列出每个键,值对.
他们的python模块是轻量级/快速的,可以很好地完成这项工作.或者任何人都有任何他们可以粘贴的简单代码可能会这样做.
解决 方案这里的所有解决方案都很有 pprint无疑是打印字典的更稳定的方法,尽管它没有返回任何接近html的东西.虽然仍然可以打印.
我现在最终得到了这个:
def printitems(dictObj, indent=0):
p=[]
p.append('<ul>\n')
for k,v in dictObj.iteritems():
if isinstance(v, dict):
p.append('<li>'+ k+ ':')
p.append(printitems(v))
p.append('</li>')
else:
p.append('<li>'+ k+ ':'+ v+ '</li>')
p.append('</ul>\n')
return '\n'.join(p)
Run Code Online (Sandbox Code Playgroud)
它将dict转换为无序列表,现在可以了.一些css,也许一点调整应该使它可读.
我将奖励写下上述代码的人的答案,我做了一些小的改动,因为无序列表没有嵌套.我希望所有人都同意所提供的许多解决方案都证明是有用的,但上面的代码呈现了字典的真正html表示,即使是粗糙的.
pyfunc制作的示例可以很容易地修改,以生成简单的嵌套html列表.
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)
Run Code Online (Sandbox Code Playgroud)
当然不是非常漂亮,但可能会在某个地方开始.如果你想做的就是可视化数据,那么pprint模块确实足够好.您可以在pprint的结果上使用"pre"标记并将其放在您的网页上.
pprint版本看起来像这样:
import pprint
z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}
print '<pre>', pprint.pformat(z), '</pre>'
Run Code Online (Sandbox Code Playgroud)
而html输出看起来像这样:
{'data': {'address': {'city': 'anycity',
'postal': 'somepostal',
'street': 'some road'},
'id': 1,
'title': 'home'}}
Run Code Online (Sandbox Code Playgroud)
这不是那么漂亮,但它至少以更有条理的方式显示数据.
import pprint
pprint.pprint(yourDict)
Run Code Online (Sandbox Code Playgroud)
好吧,没有HTML,但与你的for/print方法类似.
编辑:或使用:
niceText = pprint.pformat(yourDict)
Run Code Online (Sandbox Code Playgroud)
这将为您提供与所有缩进等相同的良好输出.现在您可以迭代行并将其格式化为HTML:
htmlLines = []
for textLine in pprint.pformat(yourDict).splitlines():
htmlLines.append('<br/>%s' % textLine) # or something even nicer
htmlText = '\n'.join(htmlLines)
Run Code Online (Sandbox Code Playgroud)
这是我的简单解决方案,它可以处理任何级别的嵌套字典。
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(' ', ' ').replace(',\n', ',<br>').replace('\n', '<br>')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14686 次 |
| 最近记录: |