0

我有一个烧瓶应用程序,它从 jsonify 函数返回输出,但显示在 html 上的输出并不漂亮。我现在解析这个输出并在将其返回到 html 之前对其进行修改。我试图迭代 json 输出,但它不允许我这样做。我怎么做?

首先是我网页上 jsonify 函数的输出

预测:苹果雪松锈,99.6459424495697,Bell_Pepper 健康,0.2868120325729251,蓝莓健康,0.05757397739216685

我想要这样的东西

预测

苹果雪松锈病:99.6459424495697

Bell_Pepper 健康:0.2868120325729251

蓝莓健康:0.05757397739216685

现在这是我的 app.py 文件中相同的代码

@app.route('/predict', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        # Get the file from post request
        f = request.files['file']

        # Save the file to ./uploads
        basepath = os.path.dirname(__file__)
        file_path = os.path.join(
            basepath, 'uploads', secure_filename(f.filename))
        f.save(file_path)

        result = model_predict(file_path, model)
        return jsonify(result)

    return None

最后是我的 main.js 文件的代码

$.ajax({
    type: 'POST',
    url: '/predict',
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    async: true,
    success: function (data) {
        // Get and display the result
        $('.loader').hide();
        $('#result').fadeIn(600);
        $('#result').text(' Prediction:  ' + data);
        console.log('Success!');
    },
});
4

2 回答 2

1

您可以返回一个 HTML 字符串,该字符串可用作#resultdiv 的主体:

在你的app.py,在upload

...
result = model_predict(file_path, model)
return flask.jsonify({'html':'\n'.join(f'<p>{a}: {b}</p>' for a, b in result)})

main.js

$.ajax({
  type: 'POST',
  url: '/predict',
  data: form_data,
  contentType: false,
  cache: false,
  processData: false,
  async: true,
  success: function (data) {
    // Get and display the result
    $('.loader').hide();
    $('#result').fadeIn(600);
    $('#result').append(data.html); //add previously formatted html to div
    console.log('Success!');
   },
});

值的 Javascript 呈现:

app.py

import json
result = model_predict(file_path, model)
return flask.jsonify({'payload':json.dumps([{'name':a, 'val':b} for a, b in result])})

main.js

$.ajax({
 type: 'POST',
 url: '/predict',
 data: form_data,
 contentType: false,
 cache: false,
 processData: false,
 async: true,
 success: function (data) {
    // Get and display the result
   $('.loader').hide();
   $('#result').fadeIn(600);
   var new_data = JSON.parse(data.payload);
   $('#result').append('Prediction: ');
   for (var i in new_data){
     var _html = `
       <p>${new_data[i].name}: ${new_data[i].val}</p>
     `
      $('#result').append(_html);
   }
   console.log('Success!');
  },
});
于 2019-06-19T00:38:55.500 回答
0

假设result是一个有效的 json 对象传入jasonify(result),您将需要遍历您的数据对象并以编程方式main.js显示对。key:value像这样的东西:

// data =  { 'Apple Cedar rust': '99.6459424495697', ...  }
$.each(data,function(key,value){
   $('#results-list').append("<span>"+ key +": " + value + "</span>")
});
于 2019-06-19T00:36:10.927 回答