【问题标题】:Ansible JSON parsing error - FAILED! => {"msg": "template error while templating string: expected name or numberAnsible JSON 解析错误 - 失败! => {"msg": "模板化字符串时出现模板错误:预期的名称或数字
【发布时间】:2020-02-08 03:23:05
【问题描述】:

我正在尝试使用 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'}}"

我收到以下错误:

致命:[本地主机]:失败! => {"msg": "模板错误,同时模板字符串:预期的名称或数字。字符串:{{response.json | json_query(\"James Params\".\"05.pincode\")}}"}

请求帮助。

【问题讨论】:

    标签: ansible ansible-2.x


    【解决方案1】:

    问:“来自 JSON 响应的密码”

    A:下面的任务

        - 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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      相关资源
      最近更新 更多