如何格式化烧瓶中的Json获取请求

时间:2019-09-21 23:52:04

标签: python-3.x flask flask-restful

我对烧瓶很陌生, 基本上我有这段代码可以返回多个值

length= len(data['hits']['hits'])


for i in range(length):
  #print(i)
  #print (data['hits']['hits'][i]['_source']['message'])
  imei=((data['hits']['hits'][i]['_source']['GPS-LOG'].get("IMEI")))
  print ("imei: {}".format(imei))
  log_time=((data['hits']['hits'][i]['_source']['@timestamp']))
  print ("log time: {}".format(log_time))

输出:-

imei: 44444
log time: 2019-09-21T23:31:28.429Z
imei: 55555
log time: 2019-09-21T23:32:02.554Z
imei: 22222
log time: 2019-09-21T23:32:04.561Z
imei: 555555
log time: 2019-09-21T23:32:14.591Z

我正在烧瓶GET方法中使用该脚本

@app.route('/battery/<string:get_imei>')
def get_battery(get_imei):
 length= len(data['hits']['hits'])
    for i in range(length):

    imei=(data['hits']['hits'][i]['_source']['GPS-LOG'].get("IMEI"))
    #print ("imei: {}".format(imei))
    log_time=((data['hits']['hits'][i]['_source']['@timestamp']))
    d = datetime.datetime.strptime(log_time,"%Y-%m-%dT%H:%M:%S.%fZ")
    new_format = "%Y-%m-%d"
    d.strftime(new_format)
    print ("log time: {}".format(d))
    return jsonify ('{} {}'.format(imei, d))

但是这不返回多个值,它也仅返回单个值我可以不使它成为json格式,例如{'imei':'22222','logtime':'2019-09-21'},...

2 个答案:

答案 0 :(得分:0)

只需用

替换return jsonify ('{} {}'.format(imei, d))
return jsonify(imei = imei, logtime = d)

应该会得到预期的结果。

答案 1 :(得分:0)

您可以使用JSON数组来做到这一点。首先,您需要遍历值列表并将字典追加到列表中,从而将每个对添加到字典中。之后,对列表进行json处理以获取所有值。 从您的代码块中,似乎只有第一个值将被返回,因为jsonify将仅以单个值(无论是列表还是其他字典)返回JSON格式。

    #say you have two lists of imei and corresponding logtime
    imei=[44444,55555,22222,55555]
    logtime=['2019-09-21T23:31:28.429Z','2019-09-21T23:32:02.554Z','2019-09-21T23:32:04.561Z','2019-09-21T23:32:14.591Z']

    #to add each entry in JSON format in an array containing two fields, you need to create a temp dict and append it in list
    result=[]

    # we need to iterate over each element and add it to the dict and then add the dict to list
    for i in range(len(imei)):
        # it is creating a temporary dict and appending it to the result list (array)
        tempDict={'imei':imei[i],'logtime':logtime[i]}
        result.append(tempDict)

    # after this return the result as JSON    
    return jsonify(result=result)

您的输出将如下所示

{"result":[{"imei":44444,"logtime":"2019-09-21T23:31:28.429Z"},{"imei":55555,"logtime":"2019-09-21T23:32:02.554Z"},{"imei":22222,"logtime":"2019-09-21T23:32:04.561Z"},{"imei":55555,"logtime":"2019-09-21T23:32:14.591Z"}]}

enter image description here

这里是类似的线程:Flask-Json How do i return mutiple rows as json objects