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>Below is the sample function to achieve this:</p>

<pre><code>def get_vote_cast_from_id(id):
    global my_json
    for name, nested_values in my_json['votes'].items():
        if any(nested_value['id'] == id for nested_value in nested_values):
            return name
    else:
        return None

get_vote_cast_from_id("A000374")
# returns: "Aye"

get_vote_cast_from_id("random_id")
# returns: None
</code></pre>

<p>where <code>my_json</code> is global variable storing your <code>JSON</code>object.</p>

python json jq