JustMe JustMe - 2 months ago 10
JSON Question

Searching JSON, Returning String within the JSON Structure

I have a set of JSON data that looks simular to this:

{"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
}


I have taken this and parsed it with Python as below:

import json
import pprint

with open('file.json') as dataFile:
data = json.load(dataFile)


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.

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

Answer

You can't do this in computational order of O(1), at least with what it is like now. The following is a solution with O(n) complexity for each search.

id = None
for dic in executions:
    if dic['issueKey'] == query:
        id = dic['id']
        break

Doing this in O(1), need a pre-processing of O(n), in which you categorize executions by their issueKey, and save inside it whatever information you want.

# Preprocessing of O(n)
mapping = dict()
for dic in executions:
    mapping[dic['issueKey']] = {
        'id':  dic['id'],
        'whatever': 'whateverel'
    }

# Now you can query in O(1)

return dic[query]['id']

You might also want to consider working with MongoDB or likes of it, if you're doing heavy json querying.