python字典到HTML无序列表



目前我正在尝试将这个python字典转换为html无序列表:

{"dataStreamId":"原始:com.google。nutrition:NutritionSource', 'dataStreamName': 'NutritionSource', 'type': 'raw', 'dataType': {'name': 'com.google。营养"、"字段":[{"名称":"营养","格式":"地图"},{"名称":"meal_type","格式":"整数"、"可选":真正的},{"名称":"food_item","格式":"弦"、"可选":真正}]},"应用程序":{"版本":"1","detailsUrl":"http://example.com"、"名称":"我的示例应用程序"},"dataQualityStandard":[]}

有以下功能:

def dict_to_html_ul(dd, level=4):
import simplejson
text = '<ul>'
for k, v in dd.items():
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

但是我得到这个结果:

<ul>
<li><b>dataStreamId</b>: raw:com.google.nutrition:NutritionSource</li>
<li><b>dataStreamName</b>: NutritionSource</li>
<li><b>type</b>: raw</li>
<li><b>dataType</b>: <ul>
<li><b>name</b>: com.google.nutrition</li>
<li><b>field</b>: [{"name": "nutrients", "format": "map"}, {"name": "meal_type", "format": "integer",
"optional": true}, {"name": "food_item", "format": "string", "optional": true}]</li>
</ul>
</li>
<li><b>application</b>: <ul>
<li><b>version</b>: 1</li>
<li><b>detailsUrl</b>: http://example.com</li>
<li><b>name</b>: My Example App</li>
</ul>
</li>
<li><b>dataQualityStandard</b>: []</li>
</ul>

和我有问题试图修复的结果,基本上我想转换结果的其余部分以相同的方式作为函数。

我尝试用一些字符串替换函数后的文本:

text = text.replace('[','').replace(']', '')
text= text.replace('{', '<br>' + '&nbsp;' * level).replace('}', '')
text = text.replace(',', '<br>' + '&nbsp;' * (level-1))

它出现了一些额外的空间,我无法替换一些部分,像这样:

"word"word"

所以我试着写一个"re.sub()"但没有成功。

编辑:

预期输出:

<ul>
<li><b>dataStreamId</b>: raw:com.google.nutrition:NutritionSource</li>
<li><b>dataStreamName</b>: NutritionSource</li>
<li><b>type</b>: raw</li>
<li><b>dataType</b>:
<ul>
<li><b>name</b>: com.google.nutrition</li>
<li><b>field</b>:
<ul>
<li><b>name</b>: nutrients</li>
<li><b>format</b>: map</li>
<br>
<li><b>name</b>: meal_type</li>
<li><b>format</b>: integer</li>
<li><b>optional</b>: true</li>
<br>
<li><b>name</b>: food_item</li>
<li><b>format</b>: string</li>
<li><b>optional</b>: true</li>
</ul>
</li>
</ul>
</li>
<li><b>application</b>: <ul>
<li><b>version</b>: 1</li>
<li><b>detailsUrl</b>: http://example.com</li>
<li><b>name</b>: My Example App</li>
</ul>
</li>
<li><b>dataQualityStandard</b>: []</li>
</ul>

Edit2:谢谢你的回答@AndrejKesely

我实际上在第一个特定的字典中得到了正确的html,但是我有另一个字典实际上不能与这个函数一起工作:-

a = {'minStartTimeNs': '1573159699023000000', 'maxEndTimeNs': '1573159699023999000', 'dataSourceId': 'raw:com.google.nutrition:NutritionSource', 'point': [{'startTimeNanos': '1573159699023000000', 'endTimeNanos': '1573159699023999000', 'dataTypeName': 'com.google.nutrition', 'value': [{'mapVal': [{'key': 'fat.total', 'value': {'fpVal': 0.4}}, {'key': 'sodium', 'value': {'fpVal': 1}}, {'key': 'fat.saturated', 'value': {
'fpVal': 0.1}}, {'key': 'protein', 'value': {'fpVal': 1.3}}, {'key': 'carbs.total', 'value': {'fpVal': 27}}, {'key': 'cholesterol', 'value': {'fpVal': 0}}, {'key': 'calories', 'value': {'fpVal': 105}}, {'key': 'sugar', 'value': {'fpVal': 14}}, {'key': 'dietary_fiber', 'value': {'fpVal': 3.1}}, {'key': 'potassium', 'value': {'fpVal': 422}}]}, {'intVal': 4, 'mapVal': []}, {'stringVal': 'apple', 'mapVal': []}]}]}

我期望一个函数可以同时用于

但是在其他字典输出中带有get_html()的输出:

<ul>
<li><b>minStartTimeNs</b>: 1573159699023000000</li>
<li><b>maxEndTimeNs</b>: 1573159699023999000</li>
<li><b>dataSourceId</b>: raw:com.google.nutrition:NutritionSource</li>
<li><b>point</b>: <ul>
<li><b>startTimeNanos</b>: 1573159699023000000</li>
<li><b>endTimeNanos</b>: 1573159699023999000</li>
<li><b>dataTypeName</b>: com.google.nutrition</li>
<li><b>value</b>: [{'mapVal': [{'key': 'fat.total', 'value': {'fpVal': 0.4}}, {'key': 'sodium', 'value':
{'fpVal': 1}}, {'key': 'fat.saturated', 'value': {'fpVal': 0.1}}, {'key': 'protein', 'value': {'fpVal':
1.3}}, {'key': 'carbs.total', 'value': {'fpVal': 27}}, {'key': 'cholesterol', 'value': {'fpVal': 0}},
{'key': 'calories', 'value': {'fpVal': 105}}, {'key': 'sugar', 'value': {'fpVal': 14}}, {'key':
'dietary_fiber', 'value': {'fpVal': 3.1}}, {'key': 'potassium', 'value': {'fpVal': 422}}]}, {'intVal':
4, 'mapVal': []}, {'stringVal': 'apple', 'mapVal': []}]</li>
</ul>
</li>
</ul>

And I was expected:

<ul>
<li><b>minStartTimeNs</b>: 1573159699023000000</li>
<li><b>maxEndTimeNs</b>: 1573159699023999000</li>
<li><b>dataSourceId</b>: raw:com.google.nutrition:NutritionSource</li>
<li><b>point</b>: <ul>
<li><b>startTimeNanos</b>: 1573159699023000000</li>
<li><b>endTimeNanos</b>: 1573159699023999000</li>
<li><b>dataTypeName</b>: com.google.nutrition</li>
<li><b>value</b>:
<ul>
<li><b>mapVal</b>:
<ul>
<li><b>key</b>: fat.total</li>
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 0.4</li>
</ul>
</li>
<br>
<li><b>key</b>: sodium</li>
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 1</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'fat.saturated',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 0.4</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'protein',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 5.4</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'carbs.total',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 6.4</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'cholesterol',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 4.5</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'calories',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 3.4</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'sugar',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 5.5</li>
</ul>
</li>
<br>
<li><b>key</b>:</li>'dietary_fiber',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 1</li>
</ul>
</li>
<br>
<li><b>key</b>:</li> 'potassium',
<li><b>value</b>:
<ul>
<li><b>fpVal</b>: 2</li>
</ul>
</li>
<br>
</ul>
<li><b>intVal</b>: 4</li>
<li><b>mapVal</b>: []</li>
<br>
<li><b>stringVal</b>: apple</li>
<li><b>mapVal</b>: []</li>
</li>
</ul>
</li>
</ul>
</li>
</ul>

尝试:

dct = {
"dataStreamId": "raw:com.google.nutrition:NutritionSource",
"dataStreamName": "NutritionSource",
"type": "raw",
"dataType": {
"name": "com.google.nutrition",
"field": [
{"name": "nutrients", "format": "map"},
{"name": "meal_type", "format": "integer", "optional": True},
{"name": "food_item", "format": "string", "optional": True},
],
},
"application": {
"version": "1",
"detailsUrl": "http://example.com",
"name": "My Example App",
},
"dataQualityStandard": [],
}

def get_html(o):
s = ""
if isinstance(o, dict):
s += "<ul>n"
for k, v in o.items():
s += f"<li><b>{k}</b>: " + get_html(v) + "</li>n"
s += "</ul>"
elif isinstance(o, list):
s += "<ul>n"
if not o:
return str(o)
else:
out = []
for v in o:
ss = ""
for kk, vv in v.items():
ss += f"<li><b>{kk}</b>: {vv}</li>n"
out.append(ss)
s += "<br>n".join(out)
s += "</ul>"
else:
return str(o)
return s

print(get_html(dct))

打印("beautified"结果):

<ul>
<li><b>dataStreamId</b>: raw:com.google.nutrition:NutritionSource</li>
<li><b>dataStreamName</b>: NutritionSource</li>
<li><b>type</b>: raw</li>
<li><b>dataType</b>:
<ul>
<li><b>name</b>: com.google.nutrition</li>
<li><b>field</b>:
<ul>
<li><b>name</b>: nutrients</li>
<li><b>format</b>: map</li>
<br>
<li><b>name</b>: meal_type</li>
<li><b>format</b>: integer</li>
<li><b>optional</b>: True</li>
<br>
<li><b>name</b>: food_item</li>
<li><b>format</b>: string</li>
<li><b>optional</b>: True</li>
</ul>
</li>
</ul>
</li>
<li><b>application</b>:
<ul>
<li><b>version</b>: 1</li>
<li><b>detailsUrl</b>: http://example.com</li>
<li><b>name</b>: My Example App</li>
</ul>
</li>
<li><b>dataQualityStandard</b>: []</li>
</ul>

多亏了@AndrejKesely,这个函数才能正常工作

def get_html(o):
s = ""
if isinstance(o, dict):
s += "<ul>n"
for k, v in o.items():
s += f"<li><b>{k}</b>: " + get_html(v) + "</li>n"
s += "</ul>"
elif isinstance(o, list):
s += "<ul>n"
if not o:
return str(o)
else:
out = []
for v in o:
ss = ""
for kk, vv in v.items():
ss += f"<li><b>{kk}</b>:" + get_html(vv) + " </li>n"
out.append(ss)
s += "<br>n".join(out)
s += "</ul>"
else:
return str(o)
return s

我对他的函数所做的唯一改动是:

for v in o:
ss = ""
for kk, vv in v.items():
ss += f"<li><b>{kk}</b>: {vv}</li>n"
out.append(ss)

变得像这样迭代:

for v in o:
ss = ""
for kk, vv in v.items():
ss += f"<li><b>{kk}</b>:" + get_html(vv) + " </li>n"
out.append(ss)

相关内容

  • 没有找到相关文章

最新更新