使用 JQ 交换嵌套对象中的键

Swap keys in nested objects using JQ

使用jq,如何转换:

{ "a": {"b": 0}, "c": {"d": 1}}

进入:

{"b": {"a": 0}, "d": {"c": 1}}

不知道源中密钥的名称?

(我知道这在一般情况下会丢失数据,但我的数据不会)

def swapper:
  . as $in
  | reduce keys[] as $key
      ( {}; . + ( $in[$key] as $o
                  | ($o|keys[0]) as $innerkey
                  | { ($innerkey): { ($key): $o[$innerkey] } } ) ) ;

示例:

{ "a": {"b": 0}, "c": {"d": 1}} | swapper

产生:

{"b":{"a":0},"d":{"c":1}}

这是使用 with_entries 的替代方法:

with_entries(.key as $parent
  | (.value|keys[0]) as $child
  | {
        key: $child,
        value: { ($parent): .value[$child] }
    }
)

这是一个使用 jq 流和变量的解决方案:

[
  . as $d
| keys[]
| $d[.] as $v
| ($v|keys[]) as $vkeys
| {
    ($vkeys): {
       (.): ($vkeys|$v[.])
    }
  }
] | add

很容易忘记最后是什么,所以为了更清楚地看到发生了什么,这里是一个带有附加注释和变量的稍微扩展的版本。

[
  . as $d                    # $d:     {"a":{"b":0},"c":{"d": 1}}
| keys[] | . as $k           # $k:     "a", "c"
| $d[$k] as $v               # $v:     {"b": 0}, {"d": 1}
| ($v|keys[]) as $vkeys      # $vkeys: "b", "d"
| ($vkeys|$v[.]) as $vv      # $vv:    0, 1
| {
    ($vkeys): {              # "b": {     "d": {
       ($k): $vv             #   "a": 0      "c": 1
    }                        # }        , }
  }
] | add