我正在尝试将Ansible脚本转换为Python AWS lambda函数。在我的Python脚本中,我使用jmespath
library按日期进行过滤,日期以ISO 8601格式的字符串形式给出。
我的过滤器可以在Ansible脚本中使用,也可以使用jmespath
。我无法弄清楚为什么我的Python版本无法正常工作。 Ansible是用Python编写的,因此我希望它能以相同的方式工作。
这在Ansible中有效:
JMESPath website tool
[当我尝试在Python中执行相同的操作时,我得到一个空列表, - 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
:
[]
示例JSON数据:
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)
使用Ansible,并在JMESPath网站上获得以下输出:
[
{
"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"
}
]
您似乎对Python的JavaScript语法感到困惑。 Python字符串中的反引号不会导致某些内容作为Python表达式内插:
[
{
"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"
}
]
是来自Python代码中的`str(compareTime)`
str(compareTime)'[?last_activity_at >
字符串。这可能适用于JavaScript,不适用于Python。
就Python而言,这只是文字文本。使用Python语法,例如]'
:
formatted string literal, or f-string
字符串文字之前的plist2 = jmespath.search(f"[?last_activity_at > '{compareTime}']", project_data)
告诉Python在f
大括号之间查找任何表达式,因此{...}
被插入字符串的该位置。我在表达式周围添加了文字compareTime
单引号,以使其成为正确的JMESPath字符串值。您也可以使用'...'
让Python提供字符串文字表示形式(在这种情况下,请不要使用单引号)。
以上显示了您的预期输出:
{compareTime!r}