无法在Flask Jinja模板中解析JSON对象

时间:2015-02-01 18:22:08

标签: python json flask jinja2

我有一个简单的JSON数据:

{"thisdata": ["/home/fyp/Desktop/AVA/AVA-STORAGE", "Network has already been configured since nexpose-pc is in virtualbox! ...", "/home/fyp/Desktop/AVA/AVA-APP/RunGUI", "ubuntu-trusty\t192.168.0.21", "", "/home/fyp/Desktop/AVA/AVA-APP/RunGUI", "centos-7\t192.168.0.22", "", "/usr/sbin/apache2", "[sudo] password for fyp: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message", "(' * Restarting web server apache2\\n   ...done.\\n', None)", "/usr/local/packer/packer", "/usr/bin/virtualbox", "centos 8 is not configured, going to install distribution", "Traceback (most recent call last):", "File \"../RunCMD/ava.py\", line 684, in <module>", "createvm.runPacker()", "File \"../RunCMD/ava.py\", line 124, in runPacker", "packer_tmp + '/' + self.Hostname + '_template.json')", "File \"/usr/lib/python2.7/shutil.py\", line 82, in copyfile", "with open(src, 'rb') as fsrc:", "IOError: [Errno 2] No such file or directory: 'TEMPLATES/redhat/template.json'"]}

我想在我的Flask应用模板中解析,但我似乎不知道该怎么做。

注意:不使用jsonify()我使用json.dumps()并将JSON发送到网页我可以打印整个JSON数据块但不格式化。

这是我的主要应用:

@app.route('/', methods=['GET', 'POST'])
def home():
    manual = HomeForm(request.form)
    automatic = Automatic(request.form)

    if request.method == 'POST':
        if 'automatic' in request.form and automatic.validate():

            run()
            data_string = []
            with open(logfile, 'r') as outfile:
                for line in outfile:
                    data_string.append(line.strip())
            json_string = jsonify({"thisdata": data_string})
            print json_string

            return render_template('index.html', form=manual, showouput='showouput', senddata=json_string)

        flash('Please input all values!')
        return render_template('index.html', form=manual)

正如您所看到的,我正在尝试运行脚本,然后使用JSON格式返回文件中的某些行,如上所示。

但是我不知道如何解析JSON,我感觉我没有以正确的方式发送JSON,而且我也不知道如何在Jinja模板中呈现JSON。

我尝试在模板中打印{{ senddata }}和其他建议,但它没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

我所要做的只是解析列表而不是json,因为我的主要动机是以div格式显示文件内容。在模板中我只渲染列表:

            data_string = []
        with open(logfile, 'r') as outfile:
            for line in outfile:
                data_string.append(line.strip())

        return render_template('index.html', form=manual, showouput='showouput', senddata=data_string)


{% if senddata %}
{% for n in senddata%}
    <div>{{ n }}</div>
{%endfor%}
{% endif %}