编辑:尝试简化我的问题,并将JSON示例简化为相关元素。
在Ansible中构建一个剧本,我要做的一项任务是从4个不同的Qradar API端点中提取数据,并尝试将每个端点的一些细节结合起来。
为每个端点提供4个不同的json来源:
)中的唯一标识符。
实验室的例子:
regex_properties.json
[
{
"identifier": "59723052-d96c-4cef-ba7b-69d426602e04",
"property_type": "numeric",
"name": "indexTotalSize",
}
]
log_sources.json
[
{
"id": 64,
"name": "SIM Audit-2 :: eng-qradar-aio-01",
"type_id": 105,
"last_event_time": 1588628234930,
}
]
log_source_types.json
[
"name": "SIM Audit",
"id": 105
},
]
property_expressions.json
[
{
"identifier": "0311c65b-d5b5-483e-943f-b539543a8e95",
"log_source_type_id": 105,
"log_source_id": 65,
"regex_property_identifier": "59723052-d96c-4cef-ba7b-69d426602e04",
}
]我想输入这4个源,并输出一个具有property_expressions.json链接的以下数据的文件:
similiar)
)
如下所示
merged_example.json
[
{
"identifier": "0311c65b-d5b5-483e-943f-b539543a8e95",
"log_source_type_id": 105,
"log_source_id": 65,
"regex_property_identifier": "59723052-d96c-4cef-ba7b-69d426602e04",
"property_type": "numeric",
"regex_name": "indexTotalSize",
"lst_name": "SIM Audit",
"ls_name": "SIM Audit-2 :: eng-qradar-aio-01",
}
]或转换成csv具有相同的数据,这是导出的最终目标,但可以等待。
我试图将regex_properties.json中的“标识符”重命名为“regex_properties.json”,然后使用'jq -s regex_properties.json property_expressions.json‘,但我仍然只看到两个内容在同一个输出/文件中是单独的数组。
我试过使用ansible并做了如下的事情:
- name: use JQ to reformat json to csv
shell: cat /tmp/property_expressions.json | jq -r '.[]' | jq 'select(.enabled == true)' | jq '[.identifier,.regex_property_identifier,.log_source_id,.log_source_type_id] | @csv' > /tmp/props.csv
- name: Read CSV into dictionary
read_csv:
path: "/tmp/props.csv"
fieldnames: "prop_id,regex_id,ls_id,lst_id"
delimiter: ","
register: props
- name: Loop Prop Dictionary and replace in CSV the regex_id
replace:
path: "/tmp/props.csv"
regexp: "{{ item.regex_id }}"
replace: "{{ regex_properties.json | json_query(regex_name_q) }},{{ regex_properties.json | json_query(regex_type_q) }}"
loop: "{{ props.list }}"
vars:
regex_name_q: "{{ item.regex_id }}.name"
regex_type_q: "{{ item.regex_id }}.property_type"为了只做一个CSV并逐项查找/替换术语。但是如果我能在JSON数组中做到这一点,那就更干净了。
发布于 2020-05-06 03:20:39
假设问题中JSON示例中的小错误,下面的bash脚本生成输出,如下所示:
#!/bin/bash
jq -n \
--argfile lst log_source_types.json \
--argfile ls log_sources.json \
--argfile pe property_expressions.json \
--argfile rp regex_properties.json '
[ range(0, $pe|length) as $i
| {identifier: $pe[$i].identifier,
log_source_type_id: $lst[$i].id,
log_source_id: $pe[$i].log_source_id,
regex_property_identifier: $pe[$i].regex_property_identifier,
property_type: $rp[$i].property_type,
regex_name: $rp[$i].name,
lst_name: $lst[$i].name,
ls_name: $ls[$i].name
}
]
'注意:我不会太担心-- are文件被正式否决了,但是如果这让您感到困扰,有很多解决办法,尽管有些是依赖于版本的。如果您想要一个不受欢迎的解决方案,该解决方案将适用于jq的每个版本,我将使用以下形式:
jq -s -f program.jq \
log_source_types.json \
log_sources.json \
property_expressions.json \
regex_properties.json其中,program.jq首先定义四个$-变量,以:.[0] as $lst |开头
https://stackoverflow.com/questions/61614422
复制相似问题