You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ServiceNow API返回结果提取为指定格式的列表?

问题描述

我需要将ServiceNow API请求的返回结果转换为指定格式的列表。API返回的JSON数据如下:

"json": {
            "result": {
                "success": "True",
                "entries": {
                    "matches": 119,
                    "records": [
                        {
                            "our_reference": "INV01567761"
                        },
                        {
                            "our_reference": "INV01134545"
                        },
                        {
                            "our_reference": "INV01345435"
                        },
                        {
                            "our_reference": "INV01345345"
                        }
                     ]
                }
            }
        }

目标是提取所有our_reference的值,形成纯字符串列表:

["INV01567761","INV01134545","INV01345435","INV01345345"]

我已通过以下Ansible代码获取到records字段的字典列表:

- name: trying to get a list
  set_fact:
    incidentList: "{{ ticketresult.json.result.entries.records }}"
- debug: var=incidentList

输出结果为:

[
                        {
                            "our_reference": "INV01567761"
                        },
                        {
                            "our_reference": "INV01134545"
                        },
                        {
                            "our_reference": "INV01345435"
                        },
                        {
                            "our_reference": "INV01345345"
                        }
                     ]

但无法批量提取所有字典中的our_reference值,仅能通过ticketresult.json.result.entries.records[0]获取第一个字典项。求简便方法将所需信息转换为目标列表格式。

解决方案

方法1:使用map+list过滤器

利用Ansible的map过滤器遍历列表元素,提取指定键值,再用list转换为纯字符串列表:

- name: Extract our_reference values
  set_fact:
    ref_list: "{{ ticketresult.json.result.entries.records | map(attribute='our_reference') | list }}"

- debug: var=ref_list

执行后ref_list即为目标格式的列表。

方法2:使用json_query过滤器

通过JMESPath语法直接提取,写法更简洁:

- name: Extract values with json_query
  set_fact:
    ref_list: "{{ ticketresult.json.result.entries.records | json_query('[*].our_reference') }}"

- debug: var=ref_list

其中[*].our_reference表示遍历列表中所有元素,提取每个元素的our_reference属性值。

内容的提问来源于stack exchange,提问作者OpaHasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:36:00