webcrew webcrew - 3 months ago 6
JSON Question

python parsing json response

I'm a newb with JSON and am trying to understand how to parse a JSON response. In the example below, I'd like to know how to retrieve the value of 'issueId':'executions':'id'? in the example below it is '8195'.....

r = requests.get(baseURL + getExecutionsForIssueId + id, auth=('user','pass'))
data = r.json()


JSON Response:
{
"status": {
"1": {
"id": 1,
"color": "#75B000",
"description": "Test was executed and passed successfully.",
"name": "PASS"
},
"2": {
"id": 2,
"color": "#CC3300",
"description": "Test was executed and failed.",
"name": "FAIL"
},
"3": {
.
.
.
}
},
"issueId": 15825,
"executions": [
{
"id": 8195,
"orderId": 7635,
"executionStatus": "-1",
"comment": "",
"htmlComment": "",
.
.
.

Answer

Your JSON object is just a dictionary in Python. Access the values you need like so:

data['executions'] yields an array of similar dictionary objects, assuming your JSON response is typed as you intended.

executions = data['executions']
order_id = executions[0]['orderId']

If you wish to loop over them to find the correct object with an id of 8195:

executions = data['executions'] # [{'id':8195,'orderId':7635,...}, {...}, ...]
for e in executions:
    if e['id'] == 8195: # e is the dict you want
        order_id = e['orderId']
Comments