Milister
Milister

Reputation: 658

Search JSON file for specific key using python

JSON file:https://1drv.ms/w/s!AizscpxS0QM4hJl99vVfUMvEjgXV3Q

i can extract TECH-XXX

#!/usr/bin/python
import sys
import json
sys.stdout = open('output.txt','wt')

datapath = sys.argv[1]
data = json.load(open(datapath))

for issue in data['issues']:
        if len(issue['fields']['subtasks']) == 0:
                print(issue['key'])

For every issue without subtasks (TECH-729 TECH-731) i want to extract TECH from

project": {
                    "avatarUrls": {
                        "16x16": "https://jira.corp.company.com/secure/projectavatar?size=xsmall&pid=10001&avatarId=10201",
                        "24x24": "https://jira.corp.company.com/secure/projectavatar?size=small&pid=10001&avatarId=10201",
                        "32x32": "https://jira.corp.company.com/secure/projectavatar?size=medium&pid=10001&avatarId=10201",
                        "48x48": "https://jira.corp.company.com/secure/projectavatar?pid=10001&avatarId=10201"
                    },
                    "id": "10001",
                    "key": "TECH",
                    "name": "Technology",
                    "self": "https://jira.corp.company.com/rest/api/2/project/10001"
                },

and customfield_10107.id

i tried with print(issue['customfield_10107']['id']) and got

./tasks1.py 1.json
Traceback (most recent call last):
  File "./tasks1.py", line 11, in <module>
    print(issue['customfield_10107']['id'])
KeyError: 'customfield_10107'

Upvotes: 0

Views: 50

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

key exists under issue and customfield_10107 exists in issue['fields']:

for issue in response["issues"]:
    # For issues without subtasks
    if len(issue['fields']['subtasks']) == 0:
        # Print custom field id
        if 'customfield_10107' in issue['fields']:
            custom_field = issue['fields']['customfield_10107']
            print custom_field['id']

        # Print key
        if 'key' in issue:
            print issue['key']

Upvotes: 1

Related Questions