我试图从下面的JSON数据字典中获取值green
。
位于http://localhost:9200/api/status的API端点给予以下数据:
{
"name":"prod01",
"uuid":"3430c40-e786-4325-bc48-e0a096956000",
"version":{
"number":"7.17.0",
"build_hash":"60a9838d21b6420bbdb5a4d07099111b74c68ceb",
"build_number":46534,
"build_snapshot":false
},
"status":{
"overall":{
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"title":"Green",
"nickname":"Looking good",
"icon":"success",
"uiColor":"secondary"
},
"statuses":[
{
"id":"core:elasticsearch@7.17.0",
"message":"Elasticsearch is available",
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"icon":"success",
"uiColor":"secondary"
},
{
"id":"core:savedObjects@7.17.0",
"message":"SavedObjects service has completed migrations and is available",
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"icon":"success",
"uiColor":"secondary"
}
]
}
}
执行此工作的test.sls文件是:
{% set json_data = salt.cp.get_url('http://localhost:9200/api/status', dest=None) | load_json %}
{% for key, value in json_data.items() %}
{% if value['state'] == 'green' %}
{{ key }}: {{ value }} (found)
{% else %}
{{ key }}: {{ value }}
{% endif %}
{% endfor %}
执行它时,我得到错误:
呈现SLS“基础:服务器盐开发测试”失败:Jinja变量“str object”没有属性“state”
1条答案
按热度按时间jyztefdp1#
你在对象
json_data
的所有键值对上循环,用json_data.items()
,所以,你不再有my_dictionary['state']
,你有一个key
,它将是state
,它的值将是green
。也就是说,您的
{"state": "green"}
不在字典的根目录中,因此您永远不会找到任何与您需要的匹配的键值对。不过,你可以做的是:
这将产生: