Home > Blockchain >  Prefix every key with jq
Prefix every key with jq

Time:06-09

I am parsing a package.json file and pulling out all the dependencies that start with @example.

package.json

{
  "name": "Example",
  "dependencies": { 
    "@example/alpha" : "1.2.3",
    "@example/bravo" : "1.2.3",
    "@example/charlie" : "1.2.3"
  }
}

The following is working fine.

jq -r '.dependencies | select(. != null) | with_entries(select(.key | contains("@example")))' package.json

This gives me:

{ 
  "@example/alpha" : "1.2.3",
  "@example/bravo" : "1.2.3",
  "@example/charlie" : "1.2.3"
}

However I also need to transform the keys, by adding a prefix of **/, so that I end up with:

{ 
  "**/@example/alpha" : "1.2.3",
  "**/@example/bravo" : "1.2.3",
  "**/@example/charlie" : "1.2.3"
}

How can I add the prefix to every key?

CodePudding user response:

You can modify .key inside your with_entries just as you can filter on it:

jq -r '
  .dependencies
  | select(. != null)
  | with_entries(
      select(.key | contains("@example"))
      | .key |= "**/\(.)"
    )' package.json
  • Related