3

Example

{
  "gp_sibling": "desired_value",
  "grand-parent": {
    "parent": [
      {
        "key": "known_value",
        "sibling": "asdf"
      }
    ]
  }
}

Problem definition

I have a large JSON. I know that key has a unique value. I need to get it’s grand-parent’s sibling key value (the value of gp_sibling key).

Now, I could grep the JSON, but I’d like to use jq. But I don’t know to achieve this (I use jq for simple queries only).

Notes

Although I know that jq can be used on Windows too, I use it on Linux only.

Post updates

  1. Removed commas from the example. Some formatting fixes.
peak
  • 105,803
  • 17
  • 152
  • 177
tukusejssirs
  • 564
  • 1
  • 7
  • 29

2 Answers2

0

If you just want to get the element gb_sibling, you could use the following:

jq .gp_sibling <file>

If you want to get it only if there is the key element with it's value, you could try this:

jq 'select(."grand-parent"?.parent?[]?.key=="known_value")|.gp_sibling' <file>

This, it filters the elements where the content of the attribute key inside parent inside grand-parent equals known_value.

From that result, gp_sibling is selected.

[NOTE]

grand-parent is quoted because the dash would cause problems otherwise.

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • 1
    I think he would like to extract the value of gp_sibling. | jq '.gp_sibling' | should be enough (tested here https://jqplay.org/#) – Marco Massetti Jan 19 '20 at 18:59
  • 1
    @MarcoMassetti You're right. I've edited the answer. – dan1st Jan 19 '20 at 19:05
  • Perfect! @dan1st, your solution works with the provided example, but I cannot make it work with the original key names ([example #2](https://jqplay.org/s/2VOZHwNn10)). There is an error: `jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at , line 1:`. Can you help me out here please? – tukusejssirs Jan 19 '20 at 19:33
  • 1
    @tukusejssirs this is because of the web UI. You should only put the thing inside the `'...'` in `filter`, not the whole command. – dan1st Jan 19 '20 at 19:36
  • Okay. I had blank output with the non-disclosed data until I added `.[]` (I missed that that whole data was square-bracketed). So in in the end, I used `[some_command] | jq -r '.[] | select(."grand-parent"?.parent?[]?.key=="known_value") | .gp_sibling'` – tukusejssirs Jan 19 '20 at 19:45
  • Yes, everything works now as expected. Thank you very much. :) – tukusejssirs Jan 19 '20 at 19:48
  • Great @dan1st :) – Marco Massetti Jan 20 '20 at 08:30
0

My reading of the question is that none of the key names except "key" is to be used in the query, and that if there were more than one "grand-parent sibling" that was a string, we'd want them all.

paths(.key? == "known_value") as $p
| getpath($p[0:-4])
| .[]
| select(type=="string")
peak
  • 105,803
  • 17
  • 152
  • 177