python: jsonify 仅显示一个输出

标签 python json flask

json 中有 10 个输出,但仅显示第一个输出。如何显示所有 10 个输出?

from collections import OrderedDict
import requests
from lxml import html


@app.route('/saptop', methods=['GET'])
def saptop():

    page_indo = requests.get('http://www.waterfrontsekuritas.com/marketview')
    indo = html.fromstring(page_indo.content)
    indo = indo.xpath('//table[@id="top-gainer"]//td/text()')

    col = ['Stockcode','Lastprice','Prevprice','pc','Change','Tfreq','Vol','Value']

    c1 = [OrderedDict(zip(col,indo))]    
    return jsonify({'Stock': c1})

当前输出仅显示第一个

{
  "Stock": [
    {
      "Stockcode": "BOSS",
      "Lastprice": "1,400",
      "Prevprice": "1,120",
      "pc": "25.00",
      "Change": "280",
      "Tfreq": "3,640",
      "Vol": "23,087,100",
      "Value": "29,132,765,000"
    }
  ]
}

更改为 c1 = [OrderedDict(zip(col,t)) for t in indo] 时,输出如下,这也是错误的,所有字符串均由字母和数字分隔:

{
  "Stock": [
    {
      "Stockcode": "B",
      "Lastprice": "O",
      "Prevprice": "S",
      "pc": "S"
    },
    {
      "Stockcode": "1",
      "Lastprice": ",",
      "Prevprice": "4",
      "pc": "0",
      "Change": "0"
    },
    {
      "Stockcode": "1",
      "Lastprice": ",",
      "Prevprice": "1",
      "pc": "2",
      "Change": "0"
    },
    {
      "Stockcode": "2",
      "Lastprice": "5",
      "Prevprice": ".",
      "pc": "0",
      "Change": "0"
    },

如何在 Flask 中正确显示所有 10 个结果?是json格式

最佳答案

您需要将列表格式转换为

indo = ['abc','123','cde','efg','112','123'][['abc','123' ],['cde','efg'],['112','123']]

对于您的示例,只需添加即可更改

indo = indo.xpath('//table[@id="top-gainer"]//td/text()')
indo = [indo[n:n+8] for n in range(0, len(indo), 8)]

关于python: jsonify 仅显示一个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48927600/

相关文章:

python - 全局错误处理程序的任何异常

python - 在输出中包括逗号、问号、感叹号(python)

json - django rest-framework api 和 unicode 字符

javascript - 通过 D3 中的嵌套为 JSON 创建键值对

python - 使用 Flask wtforms 和 GET 方法提交表单

javascript - 使用 jinja2 将 Python 字符串转为 html javascript block

python - 错误-IndentationError : unindent does not match any outer indentation level

python - 如何将文件中的二进制数据解包/转换为可读值?

python - Cython 中的 ctypedef 与 numpy : what is right convention?

javascript - 检查并增加 IndexedDB 的版本号。