如何使用JQ过滤器递归将含name属性的JSON数组转为对象
解决方案
使用以下JQ过滤器可以实现递归转换,仅将包含带name属性对象的数组转为以name值为键的对象:
def convert: if type == "array" then if all(.[]; type == "object" and has("name")) then reduce .[] as $item ({}; . + { ($item.name): ($item | del(.name) | convert) }) else map(convert) end elif type == "object" then with_entries(.value |= convert) else . end; convert
工作原理
- 递归函数定义:
convert函数遍历JSON结构的每个元素:- 数组处理:如果数组中所有元素都是带有
name属性的对象,就将数组转为对象。通过reduce迭代数组元素,用每个元素的name值作为键,移除name属性后的对象(并递归处理)作为值。如果数组不符合条件,就递归处理数组中的每个元素并保留数组结构。 - 对象处理:对对象的每个键值对,递归处理其值,保持键不变。
- 其他类型:字符串、数字等非数组/对象类型直接返回原值。
- 数组处理:如果数组中所有元素都是带有
示例验证
输入JSON:
{ "property": "value", "array1": [ { "name": "A", "propertyA1": "1", "propertyA2": "2" }, { "name": "B", "propertyB1": "1", "array2": [ { "name": "C", "propertyC1": "1", "propertyC2": "2" } ] } ] }
执行过滤器后输出:
{ "property": "value", "array1": { "A": { "propertyA1": "1", "propertyA2": "2" }, "B": { "propertyB1": "1", "array2": { "C": { "propertyC1": "1", "propertyC2": "2" } } } } }
内容的提问来源于stack exchange,提问作者urbanSoft
相关产品推荐
相关产品推荐

