来自api的ansible parse json数组回复

nha*_*nha 3 json ansible

我试图从API解析json响应.浏览器中的响应如下所示:

[{url: "abc.com/xyz"}]
Run Code Online (Sandbox Code Playgroud)

我从ansible请求它:

- name: Get url
  uri:
    url: my-url...
    method: GET
    force: yes
    return_content: yes
    #HEADER_Content-Type: "application/json"
  register: json_response
Run Code Online (Sandbox Code Playgroud)

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

- name: print reply
  debug:
    var: json_response
    verbosity: 1
Run Code Online (Sandbox Code Playgroud)

这使:

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

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

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

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

但我似乎无法访问json响应url.如果我尝试获取数组的第一个元素,我会"("这样看来它仍然是一个字符串.

- name: print reply2
  debug:
    var: json_response['content'][0]
    verbosity: 1
Run Code Online (Sandbox Code Playgroud)

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回复?

cle*_*ssi 6

我创建了一个json文件response.json,其中包含以下内容:

{
content: ({:url \"https://the-file-I-want\"})
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的剧本中我加载了文件并获得了你需要的网址,我创建了一个自定义的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]
Run Code Online (Sandbox Code Playgroud)

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

- hosts: localhost

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

  tasks:

    - debug: msg="{{ json_response.content | urlsubstr }}"
      with_dict: "{{ json_response }}"
Run Code Online (Sandbox Code Playgroud)

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

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"
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.