find element by sub-element and replace with sub-element's value

Viewed 89

To make it clear, I have the JSON array of the structure that I want to transform to different structure.

[
  {
    "a": 1,
    "b": 2,
    "c": {
      "d": 3
    },
    "e": {
      "f": 4,
      "g": {
        "d": 8
      }
    }
  },
  {
    "a": 5,
    "b": 6,
    "c": {
      "d": 7
    }
  },
  {
    "a": 9,
    "b": 10,
    "c": {
      "d": 11
    },
    "e": {
      "f": 12,
      "g": {
        "d": 13
      }
    }
  }
]

I want to transform it to :

[
  {
    "a": 1,
    "b": 2,
    "c": 3,
    "e": {
      "f": 4,
      "g": 8
    }
  },
  {
    "a": 5,
    "b": 6,
    "c": 7
  },
  {
    "a": 9,
    "b": 10,
    "c": 11,
    "e": {
      "f": 12,
      "g": 13
    }
  }
]

So each element that is of form :

"c": {
    "d": 3
}

I want to transform to:

"c": 3

It is guaranteed that the JSON will not have 'd' element in the root object.

I tried

jq  \
            'map(
                with_entries(
                    .value = if .value."$oid" ? then "ObjectId(" + .value."$oid"+ ")" else .value end
                    )
                )'

but it's not working for inner elements.

1 Answers

With a little adjustment, the accepted answer at the link @hek2mgl posted in his comment works just fine for your case.

walk(if type == "object" and keys_unsorted == ["d"] then .d else . end)

demo at jqplay.org

Related