0

Hi im am trying to parse json data and gets this error every time the element

 if ['fields']['assignee'] in each:
 TypeError: list indices must be integers or slices, not str
 >>> 

My json is this

{
"expand": "schema,names",
"startAt": 1,
"maxResults": 50,
"total": 7363,
"issues": [
    {
        "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
        "id": "591838",
        "self": "https://jira.mynet.com/rest/api/2/issue/591838",
        "key": "TEST-8564",
        "fields": {
            "summary": "delete  tables 31-03-2020 ",
            "customfield_10006": 2.0,
            "created": "2020-02-27T10:29:12.000+0100",
            "description": "A LOT OF TEXT",
            "assignee": null,
            "labels": [
                "DATA",
                "Refined"
            ],
            "status": {
                "self": "https://jira.mynet.com/rest/api/2/status/10000",
                "description": "",
                "iconUrl": "https://jira.mynet.com/",
                "name": "To Do",
                "id": "10000",
                "statusCategory": {
                    "self": "https://jira.mynet.com/rest/api/2/statuscategory/2",
                    "id": 2,
                    "key": "new",
                    "colorName": "blue-gray",
                    "name": "To Do"
                }
            }
        }
    }
 ]
}

The element in ['fields']['assignee'] is NULL in this example sometimes it is like this

"assignee": : {
                "self": "https://mynet.com/rest/api/2/user?username=xxxxxx",
                "name": "sij",
                "key": "x",
                "emailAddress": xx@mynet.com",
                "avatarUrls": {
                    "48x48": "https://mynet.com/secure/useravatar?ownerId=bdysdh&avatarId=16743",
                    "24x24": "https://mynet.com/secure/useravatar?size=small&ownerId=bdysdh&avatarId=16743",
                    "16x16": "https://mynet.com/secure/useravatar?size=xsmall&ownerId=bdysdh&avatarId=16743",
                    "32x32": "https://mynet.com/secure/useravatar?size=medium&ownerId=bdysdh&avatarId=16743"
                },
                "displayName": "Bruce Springsteen",
                "active": true,
                "timeZone": "Arctic/Longyearbyen"
            }, 

I am trying to check of assignee is null and if so print null

my code looks like this

with open('C:\\TEMP\\testdata.json') as json_file:
    data = json.load(json_file)
    for each in data['issues']:
        if ['fields']['assignee'] in each:
            print (['fields']['assignee']['name'])
        else:
            print ('null')       

I have tried to put in [0] between ['fields']['assignee']['name'] but nothing seems to help.

havmaage
  • 573
  • 7
  • 25
  • 1
    Does this answer your question? [Elegant way to check if a nested key exists in a dict?](https://stackoverflow.com/questions/43491287/elegant-way-to-check-if-a-nested-key-exists-in-a-dict) – Maurice Meyer Mar 09 '20 at 08:23

1 Answers1

0

Try with

if 'fields' in each and 'assignee' in each['fields']:

Note that you need the name of the key, not surrounded by square brackets.

Perhaps better:

for each in data['issues']:
    print(each.get('fields', {}).get('assignee', {}).get('name', 'null'))

and if you can't guarantee that 'issues' exists in data either:

for each in data.get('issues', []):
    <as before>

data.get('issues', []) returns an empty list if data['issuess'] doesn't exist.

9769953
  • 10,344
  • 3
  • 26
  • 37
  • when trying try: print(str(each['fields']['assignee']['name'])) except KeyError: print('null') i get the error print(str(each['fields']['assignee']['name'])) TypeError: 'NoneType' object is not subscriptable >>> – havmaage Mar 09 '20 at 08:54
  • @havmaage I've adjusted the code, so it's more failproof. It now always gets a default if a key does not exist, including the 'null' string at the end, so there is no need for a try-except or if-else (that is implicit in the `.get()` method). – 9769953 Mar 09 '20 at 09:21
  • NB: you don't need to convert a value explicitly to `str` inside a `print` function: print does that for you. – 9769953 Mar 09 '20 at 09:22
  • thx, i am now getting this error: print(each.get('fields', {}).get('assignee', {}).get('name', 'null')) AttributeError: 'NoneType' object has no attribute 'get' am i missing an libray class, my imports is only import json – havmaage Mar 09 '20 at 09:32
  • @havmaage That means `each` is `None`, which suggests your input data is just too messy. – 9769953 Mar 09 '20 at 09:34
  • got it i did this if each.get('fields', {}).get('assignee', {}): print(each.get('fields', {}).get('assignee', {}).get('displayName', 'null')) Thanks al lot – havmaage Mar 09 '20 at 09:48