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

时间:2015-11-04 11:05:58

标签: json jq

使用jq,我该如何转换:

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

成:

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

不知道来源中的密钥名称?

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

3 个答案:

答案 0 :(得分:1)

这是使用with_entries的替代方案:

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

答案 1 :(得分:0)

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}}

答案 2 :(得分:0)

这是一个使用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