如何用jq按键过滤嵌套JSON数组,提取有效表单字段并剔除无效节点
嵌套表单JSON提取的jq实现方案
核心处理规则
- 递归遍历所有嵌套节点,仅保留
type为radioGroup且带有有效id的题目节点 - 对每个题目的子选项数组,仅保留同时包含
type、label、value三个键、且type为radio的单选选项 - 拼接选项字符串格式为
[选项类型, 选项文本, 选项值],用逗号分隔
输出格式1:对象数组(每个单选选项对应一个对象)
可直接运行的jq语句
[ .. | select(has("id") and .id != null and .type == "radioGroup") | . as $q | ($q.subFields // [] | .[] | select(has("type") and has("label") and has("value") and .type == "radio")) | { id: $q.id, title: $q.title, description: $q.description, type: $q.type, questions: ([.type, .label, (.value | tostring)] | join(",")) } ]
语句说明
..递归遍历JSON所有嵌套节点,覆盖所有条件块、嵌套组件内的题目- 第一个
select过滤出所有符合要求的radioGroup题目 - 第二个
select过滤题目子选项里的无效节点,包括提示类UI组件、嵌套子表单等非选项内容 (.value | tostring)自动将数字类型的选项值转为字符串,避免拼接报错
输出格式2:简化数组(每个题目对应一个数组)
可直接运行的jq语句
[ .. | select(has("id") and .id != null and .type == "radioGroup") | [ .id, .title, .description, .type, (.subFields // [] | .[] | select(has("type") and has("label") and has("value") and .type == "radio") | [.type, .label, (.value | tostring)] | join(",")) ] ]
语句说明
- 过滤逻辑和第一种格式完全一致
- 直接将题目基础信息和所有选项字符串按顺序合并为单个数组
注:如果不需要提取嵌套条件块内的题目(例如示例中
signer_type条件下的question_4),可将递归遍历的..替换为.subFields[],仅处理顶层题目。
内容的提问来源于stack exchange,提问作者Joao Nunes
相关产品推荐
相关产品推荐

