python:jsonify只显示一个输出

时间:2018-02-22 12:37:05

标签: 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"
    }
  ]
}

change to 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格式

1 个答案:

答案 0 :(得分:1)

您需要从

转换列表格式

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)]