如何使用jq将嵌套对象迁移至不同对象并重构JSON结构
使用jq重构JSON结构:分离活跃对象与废弃对象
需求说明
需要重构JSON文件优化数据表示,将同类对象归组到父对象中,不再依赖对象的特定属性。最终结构包含5个顶级区域:
attributes、associatedObjects、inheritedObjects、enumerations:存储活跃对象deprecations:包含上述四个子分组,存储待移除的废弃对象
原始JSON结构
{ "attributes": { "alpha": { "deprecated": true, "description": "A description of alpha.", "dataType": "string" }, "beta": { "deprecated": false, "description": "A description of beta.", "dataType": "associated object", "associatedObject": "gamma" }, "kappa": { "deprecated": false, "description": "A description of kappa.", "dataType": "string" } } }
目标JSON结构
{ "deprecations": { "attributes": { "alpha": { "description": "A description of alpha.", "dataType": "string" } }, "enumerations": {}, "associatedObjects": {}, "inheritedObjects": {} }, "attributes": { "kappa": { "description": "A description of kappa.", "dataType": "string" } }, "enumerations": {}, "associatedObjects": { "beta": { "description": "A description of beta.", "dataType": "gamma" } }, "inheritedObjects": {} }
当前问题
目前仅能通过jq '.associatedObjects = {} | .inheritedObjects = {} | .enumerations = {} | .deprecations = {} '在attributes同级添加空的新区域,但无法正确迁移标记为deprecated的对象。尝试的命令生成无效JSON且结构重复,也无法和创建新区域的命令结合:
jq '.attributes | keys[] as $k | if (.[$k].deprecated == true) then (del(.[$k].deprecated) | .deprecated += .[$k] | del(.[$k])) else empty end '
解决方案
可以使用以下jq命令完成完整的结构重构,包含分离废弃对象、迁移关联对象、初始化空结构三个核心步骤:
jq ' # 初始化所有需要的空结构 .associatedObjects = {} | .inheritedObjects = {} | .enumerations = {} | .deprecations = {attributes: {}, associatedObjects: {}, inheritedObjects: {}, enumerations: {}} # 处理attributes中的废弃对象:迁移到deprecations并从原属性移除 | (.attributes | to_entries[] | select(.value.deprecated)) as $deprecated_attr | .deprecations.attributes[$deprecated_attr.key] = ($deprecated_attr.value | del(.deprecated)) | del(.attributes[$deprecated_attr.key]) # 处理attributes中的关联对象:迁移到associatedObjects并调整dataType | (.attributes | to_entries[] | select(.value.dataType == "associated object")) as $assoc_obj | .associatedObjects[$assoc_obj.key] = ($assoc_obj.value | del(.associatedObject, .deprecated) | .dataType = .associatedObject) | del(.attributes[$assoc_obj.key]) ' input.json
命令解释
- 初始化空结构:先创建所有需要的顶级对象和
deprecations的子结构,确保基础框架完整。 - 分离废弃对象:遍历
attributes中标记为deprecated: true的条目,将其移除deprecated字段后迁移到deprecations.attributes,同时从原attributes中删除该条目。 - 迁移关联对象:筛选
attributes中dataType为associated object的条目,删除associatedObject和deprecated字段,并将dataType替换为associatedObject的值,然后迁移到associatedObjects,最后从原attributes中删除该条目。
内容的提问来源于stack exchange,提问作者Timbuck
相关产品推荐
相关产品推荐

