来自api的ansible parse json数组回复

时间:2016-12-02 21:37:54

标签: json ansible

我正在尝试从API解析json响应。浏览器中的响应如下所示:

[{url: "abc.com/xyz"}]

我从ansible请求它:

- name: Get url
  uri:
    url: my-url...
    method: GET
    force: yes
    return_content: yes
    #HEADER_Content-Type: "application/json"
  register: json_response

我得到了ansible的回复,看起来像这样(带有调试):

- name: print reply
  debug:
    var: json_response
    verbosity: 1

给出:

 ok: [server] => {
     "json_response": {
         ... //removed for readability
         "content": "({:url \"https://the-file-I-want\"})"
         }

所以似乎已经发生了一些解析(请注意冒号:)。

访问内容似乎有效(使用调试json_response['content']):

ok: [server] => {
    "json_response['content']": "({:url \"https://the-file-I-want\"})"
}

但我似乎无法访问json响应url。如果我尝试获取数组的第一个元素,我得到"("所以看起来它仍然是一个字符串。

- name: print reply2
  debug:
    var: json_response['content'][0]
    verbosity: 1

from_json似乎不起作用:fatal: [server]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. ...

如何解析像这样的json回复?

1 个答案:

答案 0 :(得分:6)

我创建了一个带有以下内容的json文件response.json:

{
content: ({:url \"https://the-file-I-want\"})
}

然后,在我的剧本中我加载了文件并获得了你需要的网址,我创建了一个自定义的jinja过滤器,因为Jinja2没有任何过滤器来查找子字符串或正则表达式。

我的名为filter.py的自定义过滤器(您可以将其命名为)位于与我的playbook相同的目录中名为filter_plugins的目录中。我的filter.py文件如下:

import re
class FilterModule(object):
''' Custom filters are loaded by FilterModule objects '''

def filters(self):
    return {'urlsubstr': self.urlsubstr}
def urlsubstr(self,content):
    url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', content)
    return url[0]

创建自定义过滤器后,我得到了这样的网址:

- hosts: localhost

  vars:
    json_response: "{{ lookup('file', 'response.json') | from_json }}"

  tasks:

    - debug: msg="{{ json_response.content | urlsubstr }}"
      with_dict: "{{ json_response }}"

这是运行我的剧本的输出:

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => (item={'value': u'({:url "https://the-file-I-want"})', 'key': u'content'}) => {
    "item": {
        "key": "content",
        "value": "({:url \"https://the-file-I-want\"})"
    },
    "msg": "https://the-file-I-want"
}

希望这会有所帮助。

相关问题