Home > Software design >  Recursively replace value with $path in JQ
Recursively replace value with $path in JQ

Time:11-03

Assuming that i have a complex JsonObject

{
  "parent": {
    "name": "value",
    "child": {
      "child_value1": "value",
      "child_value2": "value",
      "child_value3": ["value1","value2"],
      "child_value4": {
         "child_child_value1":"value"
      }
    }
  }
}

I want to replace the value of each key, with the name of key prefixed with $

{
  "parent": {
    "name": "$name",
    "child": {
      "child_value1": "$child_child_value1",
      "child_value2": "$child_child_value2",
      "child_value3": ["$child_child_value3_0","$child_child_value3_1"],
      "child_value4": {
         "child_child_value1":"$child_child_value4_child_child_value1"
      }
    }
  }
}

Is there a way to do it recursively?

CodePudding user response:

You're looking for something like this:

.parent |=
  reduce paths(strings) as $p (.;
    setpath($p; "$"   ($p | join("_")))
  )

Online demo

  • Related