JMESPath 日期筛选



我正在尝试将Ansible脚本转换为Python AWS lambda函数。 在我的 Python 脚本中,我使用jmespath库按日期过滤,日期以 ISO 8601 格式的字符串形式给出。

我的过滤器在我的 Ansible 脚本中工作,也使用 JMESPath 网站工具。我不知道为什么我的 Python 版本不起作用;Ansible 是 Python 编写的,所以我希望它能以同样的方式工作。

这在 Ansible 中有效:

- name: parse groups
debug:
msg: "{{ results_gitlabGroupsProjects | to_json | from_json  | json_query(projects_query) }}"
vars:
projects_query: "json[?last_activity_at > `{{gitlab_date}}`].{name: name, id: id, last_activity_at: last_activity_at }"
register: gitlabGroupsProjects2

当我尝试在 Python 中做同样的事情时,我得到一个空列表,[]

compareTime="2020-01-15T17:55:3S.390Z"
plist2 = jmespath.search('[?last_activity_at > `str(compareTime)`]', project_data )
with open('plist2.json', 'w') as json_file:
json.dump(plist2, json_file)

示例 JSON 数据:

[
{
"name": "test",
"id": 16340975,
"last_activity_at": "2020-01-15T20:12:49.775Z"
},
{
"name": "test1",
"id": 11111111,
"last_activity_at": "2020-01-15T15:57:29.670Z"
},
{
"name": "test2",
"id": 222222,
"last_activity_at": "2020-01-15T23:08:22.313Z"
},
{
"name": "test3",
"id": 133333,
"last_activity_at": "2020-01-15T22:28:42.628Z"
},
{
"name": "test4",
"id": 444444,
"last_activity_at": "2020-01-14T02:20:47.496Z"
},
{
"name": "test5",
"id": 555555,
"last_activity_at": "2020-01-13T04:54:18.353Z"
},
{
"name": "test6",
"id": 66666666,
"last_activity_at": "2020-01-12T07:12:05.858Z"
},
{
"name": "test7",
"id": 7777777,
"last_activity_at": "2020-01-10T20:52:32.269Z"
}
]

使用 Ansible,在 JMESPath 网站上,我得到以下输出:

[
{
"name": "test",
"id": 16340975,
"last_activity_at": "2020-01-15T20:12:49.775Z"
},
{
"name": "test2",
"id": 222222,
"last_activity_at": "2020-01-15T23:08:22.313Z"
},
{
"name": "test3",
"id": 133333,
"last_activity_at": "2020-01-15T22:28:42.628Z"
}
]

你不能只是把一个str(compareTime)表达式作为字符串文字,然后让Python明白这就是你想要替换的。

在字符串中

'[?last_activity_at > `str(compareTime)`]'

没有什么是动态的;字符str(compareTime)对Python没有特殊意义。

在 Ansible 中,您使用了特殊的语法{{gitlab_date}}来告诉Ansible以不同的方式处理字符串,并且gitlab_date变量的值在此时放入字符串中,然后再将其用作 JMESPath 查询。

在Python中,你需要类似的东西。 例如,您可以使用格式化字符串文字或f 字符串

plist2 = jmespath.search(f"[?last_activity_at > `{compareTime}`]", project_data)

字符串文本之前的f告诉 Python 查找{...}大括号之间的任何表达式,因此compareTime在字符串的该点插入到位。这很像 Ansible 语法。

以上生成您的预期输出:

>>> jmespath.search(f"[?last_activity_at > `{compareTime}`]", project_data)
[{'name': 'test', 'id': 16340975, 'last_activity_at': '2020-01-15T20:12:49.775Z'}, {'name': 'test2', 'id': 222222, 'last_activity_at': '2020-01-15T23:08:22.313Z'}, {'name': 'test3', 'id': 133333, 'last_activity_at': '2020-01-15T22:28:42.628Z'}]
>>> from pprint import pprint
>>> pprint(_)
[{'id': 16340975,
'last_activity_at': '2020-01-15T20:12:49.775Z',
'name': 'test'},
{'id': 222222,
'last_activity_at': '2020-01-15T23:08:22.313Z',
'name': 'test2'},
{'id': 133333,
'last_activity_at': '2020-01-15T22:28:42.628Z',
'name': 'test3'}]

最新更新