【问题标题】:json2html from json file (python on server side)来自json文件的json2html(服务器端的python)
【发布时间】:2017-02-17 04:57:14
【问题描述】:

我有传递 json 文件的 python 代码

def home():
    with open('file.json', 'a+') as f:
        return render_template('index.html', json_data=f.read())

文件如下所示

{"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]}

在客户端,我写了这段代码

<table id="placar" class="table table-condensed  table-bordered">
      <thead>
        <tr>
          <th>shortname</th>
          <th>longname</th>
          <th>ipadress</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
</div>
<script>
var data = {{ json_data }}


var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${shortname}"
    }, {
        "tag": "td",
            "html": "${ipadr}"
    }, {
        "tag": "td",
            "html": "${longname}"
    }]
};

$('#placar > tbody ').json2html(data, transform);
</script>

但它不适用于我的文件,如果编写简单的数组它可以完美地工作。谁能说出我做错了什么,传递文件或创建表格?

【问题讨论】:

  • dmp=Json.dumps(Any_python_dict), with open('file.json', 'r') as f: 忽略EOF

标签: javascript jquery python json


【解决方案1】:

请尝试

import json
def home():
  with open('file.json', 'a+') as f:
    return render_template('index.html', json.dumps(f.read()))

【讨论】:

    【解决方案2】:

    你会想要转换 data.hosts 而不仅仅是像这样的数据对象

    $('#placar > tbody ').json2html(data.hosts, transform);
    

    这样你就可以拥有了

    var data = {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]};
    
    var transform = {
        tag: 'tr',
        children: [{
            "tag": "td",
                "html": "${shortname}"
        }, {
            "tag": "td",
                "html": "${ipadr}"
        }, {
            "tag": "td",
                "html": "${longname}"
        }]
    };
    
    $('#placar > tbody ').json2html(data.hosts, transform);
    

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多