Retrieve a value in Json based on a nested value
<p>I would like is to retrieve the vote cast given a specific id, the data (compliments to <a href="https://www.govtrack.us/" rel="nofollow">govtrack.us</a>) is stored in json and I am writing in python and intend to use <a href="https://stedolan.github.io/jq/" rel="nofollow">js</a>.</p>

<p>For example the input "Y000062" should yield "Aye"</p>

<pre><code>{
  "bill": {
    "congress": 114,
    "type": "hr"
  },
  "category": "passage",
  "votes": {
    "Aye": [
      {
        "display_name": "Abraham",
        "id": "A000374",
      },
      {
        "display_name": "Yarmuth",
        "id": "Y000062",
      }
    ],
    "Nay": [
      {
        "display_name": "Clyburn",
    "id": "C000537",
      },
    ]}}
</code></pre>

<p>In terminal a solution is cat /ccc/114/votes/2015/H384/data.json | egrep 'Nay|Not Voting|Present|Yea|Aye|Y000062' | grep -B 1 'Y000062' | head -1
but relaying that into a python subprocess seems like a clunky solution.</p>

<p>Noted: In Json {} is an Object, [] is an Array</p>

<p>Here are three solutions using jq.  If an individual is constrained to vote exactly once, then the results should be the same; otherwise, they may differ, e.g if an individual is recorded as voting both Aye and Nay.</p>

<p>The first solution assumes that each person votes at most once. If this assumption is satisfied, then it is also the most efficient because it uses <code>any/1</code>, which has "short-circuit" semantics:</p>

<pre><code>$ jq  --arg id Y000062 '.votes
| if any( .Aye[]; select(.id == $id) ) then "Aye" 
elif any( .Nay[]; select(.id == $id) ) then "Nay"
else "none"
end' votes.json
</code></pre>

<p>The next solution reports "Aye" for each occurrence of the individual on the Ayes list, and only proceeds to do likewise for the Nays list if no occurrences on the Ayes list were found:</p>

<pre><code>$ jq  --arg id Y000062 '.votes
| ((.Aye[] | select(.id == $id) | "Aye") // 
   (.Nay[] | select(.id == $id) | "Nay")) ' votes.json
</code></pre>

<p>The third solution might be appropriate if there are no constraints on how many times an individual can appear on the two lists. It first constructs a stream of [ VOTE, ID ] pairs, and then selects the IDs of interest:</p>

<pre><code>$ jq --arg id Y000062 '.votes
| ((.Nay[] | ["Nay", .id]),
   (.Aye[] | ["Aye", .id])))
| select(.[1] == $id)
| .[0]' votes.json
</code></pre>

<p>With the given input (altered slightly to make it valid JSON), the output of all three solutions is:</p>

<pre><code>"Aye"
</code></pre>

<p>(You can use a command-line tool such as <code>hjson</code> to convert the JSON-with-extra-commas to JSON.)</p>

python json jq