Jq: How to move the child members to parent?

霸气de小男生 提交于 2020-01-24 12:47:05

问题


Consider the following json:

{
  a: {
    b: {
      c: 1,
      d: 2
    }
  }
}

How can I move all the properties of b to be under the parent a:

{
  a: {
    c: 1,
    d: 2,
    b: {}
  }
}

回答1:


For this particular case, you could do this:

$ jq '.a |= (.b = {}) + .b' input.json

Here we're updating object a with the original contents with b replaced with an empty object and combining it with the contents of the original b.

If that was too hard to reason about, this might be easier to follow:

$ jq '.a |=
    with_entries(if .key == "b"
        then (.value = {}), (.value | to_entries[])
        else .
    end)' input.json



回答2:


This is just a variant of @Jeff-Mercado's first solution, but may be slightly easier to follow (notably because there is only one reference to .b, and because the grouping on the RHS is explicit):

 .a |= ({b:{}} + .b)



回答3:


To do this recursively for any field use:

walk
(
    if (type == "object" and has("b")) then
        .|=.b
    else
        .
    end
)


来源:https://stackoverflow.com/questions/42214984/jq-how-to-move-the-child-members-to-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!