skip to Main Content

Consider the following file.json where "x" is a known string. Two questions:

  1. I want to obtain a list of all the unique values in the child arrays. What I have is jq -r '.x[][] file.json | sort | uniq. Is there a native solution?

  2. I want to choose keys "a" and "c" based on the fact that they both have "3" in their respective child arrays. How do I go about that? I can get the child arrays with "3" in them with jq -r '.x[] | select(index("3") >= 0)' file.json but I need access to the parent key.

{
  "x": {
    "a": [
      "2",
      "3"
    ],
    "b": [
      "1",
      "2"
    ],
    "c": [
      "3",
      "4"
    ]
  }
}

3

Answers


  1. Chosen as BEST ANSWER
    1. jq -r '.x | with_entries(select(.value | index("3"))) | keys[]' seems to do the trick.

  2. For the first, getting the unique values of the child arrays:

    $ jq '[.x | to_entries[] | .value] | flatten | unique' input.json
    [
      "1",
      "2",
      "3",
      "4"
    ]
    

    or if you want the results one element per line instead of as JSON:

    jq -r '[.x | to_entries[] | .value] | flatten | unique[]' input.json
    1
    2
    3
    4
    
    Login or Signup to reply.
    1. I want to obtain a list of all the unique values in the child arrays. What I have is jq -r '.x[][] file.json | sort | uniq. Is there a native solution?

    Yes, jq has its own unique filter (which also sorts its input automatically). Collect all the items with […] into a single array before using it.

    jq -r '[.x[][]] | unique[]' file.json
    
    1
    2
    3
    4
    

    Demo


    1. I want to choose keys "a" and "c" based on the fact that they both have "3" in their respective child arrays. How do I go about that? I can get the child arrays with "3" in them with jq -r '.x[] | select(index("3") >= 0)' file.json but I need access to the parent key.

    You could iterate over the (sorted) keys (use keys_unsorted instead if you want the original order), and use IN (which is just a shortcut to any using == as comparator) to select by containedness.

    jq '.x | keys[] as $k | select(IN(.[$k][]; "3")) | $k' file.json
    
    a
    c
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search