如何使用 python 按行的值筛选 REST API 行响应



>我配置了一个连接到 Oracle 服务云的 REST API POST 请求,它以以下 JSON 格式接收响应:

{"count":16,"name":"Report Name","columnNames":["Connection","Complete Name","Login ID","Login Time","Logout Time","IP Direction"],"rows":[["PGALICHI","Robert The IT Guy","3205","2018-01-25 08:52:23","2018-01-25 15:00:50","201.255.56.151"],["PGALICHI","Lucas The other IT Guy","3204","2018-01-25 08:52:21","2018-01-25 15:00:51","201.255.56.151"]],"links":[{"rel":"self","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"canonical","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"describedby","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/metadata-catalog/analyticsReportResults","mediaType":"application/schema+json"}]}

此信息将成为仅打印行的脚本的输入,我现在需要的是,首先,按"登录时间"对所有行进行排序,然后,过滤"登录时间"等于或早于变量的所有值将具有最后一个"登录时间"的值。

这是我现在用来仅获取行的代码示例:

class OracleORNHandler:
def __init__(self,**args):
    pass
def __call__(self, response_object,raw_response_output,response_type,req_args,endpoint):
    if response_type == "json":        
        output = json.loads(raw_response_output)
        for row in output["rows"]:
            print_xml_stream(json.dumps(row))                      
    else:
        print_xml_stream(raw_response_output) 

这需要更多的编码。但是,我将解释逻辑方法。您可能希望稍微改变编码方法。

  1. 将字符串加载到字典中。

固定字符串

json_out = '{"count":16,"name":"Report Name","columnNames":["Connection","Complete Name","Login ID","Login Time","Logout Time","IP Direction"],"rows":[["PGALICHI","Robert The IT Guy","3205","2018-01-25 08:52:23","2018-01-25 15:00:50","201.255.56.151"],["PGALICHI","Lucas The other IT Guy","3204","2018-01-25 08:52:21","2018-01-25 15:00:51","201.255.56.151"]],"links":[{"rel":"self","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"canonical","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"describedby","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/metadata-catalog/analyticsReportResults","mediaType":"application/schema+json"}]}'
dic_json = json.loads(json_out)
  1. rows转换为字典

登录时间用作值,因为我们稍后需要它进行排序。

使用 datetime 将字符串转换为日期

from datetime import datetime
rows_list = dic_json['rows']
d = dict()
for x in rows_list:
    datetime_object = datetime.strptime(x[4], '%Y-%m-%d %H:%M:%S')
    d[x.__str__()] = datetime_object 

注意:由于登录时间可能是唯一的,也可能不是唯一的,我选择整个列表作为密钥甚至不确定登录ID在这里是唯一的。

  1. 使用collections.OrderedDict按时排序。

import collections
# sort by time i.e dictionary values
od2 =collections.OrderedDict(sorted(d.items(), key=lambda t: t[1]))
  1. 根据日期时间条件筛选值。

Input_time date_time_req = datetime.strptime('2018-01-25 08:52:23', '%Y-%m-%d %H:%M:%S')

for y in od2.keys():
    if od2[y] <= date_time_req:
        print(y)

此输出为字符串,您可以修剪并转换回列表。

最新更新