我正在使用 Flask 构建网页,并且我有一个 python 语法:
@app.route('/uploads/<filename>')
def uploaded_file(filename):
reader = shapefile.Reader("./uploads/"+filename)
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", \
geometry=geom, properties=atr))
json_string = json.dumps(buffer)
return render_template('view.html',r = json_string))
它给出像
这样的 json 响应[{"type": "Feature", "geometry": {"type": "Point", "coordinates": [595371.8167114258, 28460830.87548828]}, "properties": {"Enabled": 1}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [595508.9202880859, 28465509.365478516]}, "properties": {"Enabled": 1}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [595478.0269165039, 28465540.729675293]}, "properties": {"Enabled": 1}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [595594.5479125977, 28465644.839111328]}, "properties": {"Enabled": 1}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [595690.145690918, 28465719.45727539]}, "properties": {"Enabled": 1}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [596209.5372924805, 28465729.346679688]}, "properties": {"Enabled": 1}}, .....etc
我想用 miranda.js 以 html 表格格式打印
<table class="table table-bordered" id="myTable">
<thead>
<tr>
<th>TYPE</th>
<th>GEOMETRY</th>
<th>GEOMETRY TYPE</th>
<th>COORDINATES</th>
</tr>
</thead>
<tbody id="mydata">
<tr>
<td>[[type]]</td>
<td>[[geometry]]</td>
<td>[[type]]</td>
<td>[[coordinates]]</td>
</tr>
</tbody>
</table>
$("#mydata").mirandajs("{{r}}");
但是什么也没发生。我只是想要一种方法来解析这个 python obj json 到 html 表。你能告诉我我哪里做错了吗?或者你能告诉我一种轻松完成工作的方法
最佳答案
最简单的方法是为 json
数据创建一个类并使用内置的 jinja
模板。另外,似乎关键的“几何”:
class Stat:
def __init__(self, stat):
self.__dict__ = {a:Stat(b) if isinstance(b, dict) else b for a, b in stat.items()}
class Stats:
def __init__(self, full_data):
self.full_data = full_data
def __iter__(self):
for i in self.full_data:
yield Stat(i)
然后,调用render_template
并传递类实例:
return render_template('view.html',r = Stats(json_string)))
最后,在 view.html
中,应用 jinja
模板:
<table class="table table-bordered" id="myTable">
<thead>
<tr>
<th>TYPE</th>
<th>GEOMETRY TYPE</th>
<th>COORDINATES</th>
</tr>
</thead>
<tbody id="mydata">
{%for data in r%}
<tr>
<td>{{data.type}}</td>
<td>{{data.geometry.type}}</td>
<td>{{data.geometry.coordinates}}</td>
</tr>
{%endfor%}
</tbody>
</table>
关于javascript - 将python的json对象转换为html表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734227/