Ansible JSON 解析错误 - 失败! => {"msg": "模板化字符串时出现模板错误:预期的名称或数字

Ansible JSON parsing error - FAILED! => {"msg": "template error while templating string: expected name or number

我正在尝试使用 Ansible 解析我的 JSON,但遇到了问题。我需要来自 JSON 响应

的密码

我的示例 JSON 响应是

{
"James Params": {
"01. name": "james bond",
"02. phone": "334455667788",
"03. height": "5.10",
"04. country": "UK",
"05. pincode": "10000",
"06. city": "london",
}
}

我的剧本代码是

- name: Submit and read the JSON response
  uri:
    method: GET
    url: "http://URL_UNDER_TEST"
    return_content: yes
    headers:
      Accept: application/json
  register: response

- debug:
    msg: "{{response.json.'James Params'.'05. pincode'}}"

我收到以下错误:

fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{response.json | json_query(\"James Params\".\"05. pincode\")}}"}

请求帮助。

Q: "pincode from the JSON response"

答:下面的任务

    - debug:
        msg: "{{ response.json['James Params']['05. pincode'] }}"
    - debug:
        msg: "{{ name }} PIN is {{ response.json[name][pincode_key] }}"
      vars:
        name: 'James Params'
        pincode_key: '05. pincode'
    - debug:
        msg: "{{ name }} PIN is {{ response.json[name][pincode_key] }}"
      vars:
        name: "{{ response.json.keys()|list|first }}"
        pincode_key: '05. pincode'
    - debug:
        msg: "{{ item }} PIN is {{ response.json[item]['05. pincode'] }}"
      loop: "{{ response.json.keys()|list }}"

给予

ok: [localhost] => {
    "msg": "10000"
}

ok: [localhost] => {
    "msg": "James Params PIN is 10000"
}

ok: [localhost] => {
    "msg": "James Params PIN is 10000"
}

ok: [localhost] => (item=James Params) => {
    "msg": "James Params PIN is 10000"
}