Searching JSON, Returning String within the JSON Structure
<p>I have a set of JSON data that looks simular to this:</p>

<pre><code>{"executions": [
{
  "id": 17,
  "orderId": 16,
  "executionStatus": "1",
  "cycleId": 5,
  "projectId": 15006,
  "issueId": 133038,
  "issueKey": "QTCMP-8",
  "label": "",
  "component": "",
  "projectKey": "QTCMP",
  "executionDefectCount": 0,
  "stepDefectCount": 0,
  "totalDefectCount": 0
},
{
  "id": 14,
  "orderId": 14,
  "executionStatus": "1",
  "cycleId": 5,
  "projectId": 15006,
  "issueId": 133042,
  "issueKey": "QTCMP-10",
  "label": "",
  "component": "",
  "projectKey": "QTCMP",
  "executionDefectCount": 0,
  "stepDefectCount": 0,
  "totalDefectCount": 0
    }
  ],
  "currentlySelectedExecutionId": "",
  "recordsCount": 4
}
</code></pre>

<p>I have taken this and parsed it with Python as below:</p>

<pre><code>import json
import pprint

with open('file.json') as dataFile:
    data = json.load(dataFile)
</code></pre>

<p>With this I am able to find sets of data like executions by doing data["executions"] etc.. What I need to be able to do is search for the string "QTCMP-8" within the structure, and then when I find that specific string, find the "id" that is associated with that string. So in the case of QTCMP-8 it would be id 17; for QTCMP-10 it would be 14.</p>

<p>Is this possible? Do I need to convert the data first? Any help is greatly appreciated!</p>

<p>You can get the list of all ids as:</p>

<pre><code>&gt;&gt;&gt; [item['id'] for item in my_json['executions'] if item['issueKey'].startswith('QTCMP')]
[17, 14]
</code></pre>

<p>where <code>my_json</code> is the variable storing your JSON structure</p>

<p><strong>Note:</strong> I am using <code>item['issueKey'].startswith('QTCMP')</code> instead of <code>'QTCMP' in item['issueKey']</code> as you need id of items starting with <code>QTCMP</code>. For example, if the value is <code>XXXQTCMP</code>, it's id should not present with the result (but it will result as <code>True</code> on using <code>in</code> statement)</p>

python json