JAne
JAne

Reputation: 97

Create new JSON depending on value entry using jq

I have the below JSON

{
  "com-abc": {
    "componentName": "com-abc",
    "shortName": "abc",
    "tag": "1234",
    "commitId": "bb59d7c",
    "repository": "com-abc"
  },
  "com-def": {
    "componentName": "com-def",
    "shortName": "def",
    "tag": "5678",
    "commitId": "bb59d7cwfer",
    "repository": "com-def"
  },
  "com-ghi": {
    "componentName": "com-ghi",
    "shortName": "ghi",
    "tag": "91011",
    "commitId": "b55cwfer",
    "repository": "com-ghi"
  },
  "com-jkl": {
    "componentName": "com-jkl",
    "shortName": "jkl",
    "tag": "9107766",
    "commitId": "b55cwfer10f",
    "repository": "com-jkl"
  }
}

My query:

In the value , there is parameter "shortName" . I am trying to use jq to create a new json if the 'shortName' matches a particular value. For example, if i pass shortName as 'ghi' the new json should only contain the below sample. I'm trying to use jq here.

{
  "com-ghi": {
    "componentName": "com-ghi",
    "shortName": "ghi",
    "tag": "91011",
    "commitId": "b55cwfer",
    "repository": "com-ghi"
  }
}

Upvotes: 1

Views: 303

Answers (2)

Inian
Inian

Reputation: 85895

You can use to_entries() to create a key/value pair from the JSON objects and match the .shortName field against the string needed and use from_entries to convert the key value pair back to actual JSON

jq 'to_entries | map( select( .value.shortName == "ghi" ) ) | from_entries'

or with providing argument string from command-line using the --arg field. With that sn becomes the variable that contains the string ghi, which can be used inside the filter.

jq --arg sn ghi 'to_entries | map( select( .value.shortName == $sn ) ) | from_entries' json

See it working for a single string match at jq-playground

If you are looking for multiple condition matches, use the boolean and/or statements inside the filter

select( .value.shortName == "ghi" or .value.shortName == "abc" )

Or use the regex to exact match the strings inside the test()

select( .value.shortName | test("^(abc|ghi)$") )

Upvotes: 1

peak
peak

Reputation: 117017

Here's a solution in the case of "ghi":

jq --arg sn ghi '
    with_entries(select(.value.shortName == $sn))' input.json

Here, --arg sn ghi has the effect of setting the jq variable $sn to the JSON string "ghi".

Upvotes: 1

Related Questions