Search code examples
pythonjsonjsonparser

Parse JSON devOps API in a loop


I have a json file (part of it is below):

{
    "count": 12,
    "value": [
        {
            "id": 1,
            "workItemId": 1,
            "rev": 1,
            "fields": {
                "System.Id": {
                    "newValue": 1
                },
                "System.AreaId": {
                    "newValue": 2
                },           
        {
            "id": 2,
            "workItemId": 2,
            "rev": 2,
            "fields": {
                "System.Rev": {
                    "oldValue": 1,
                    "newValue": 2
                },
                "System.State": {
                    "oldValue": "New",
                    "newValue": "Qualification"
                }
            }}}}}

I need to retrieve System.State with the following loop:

for i in json['value']:
    for item in i['fields']:
        print(i['System.State']['newValue'])

Unfortunatelly there is a KeyError 'fields' and I don't know why.

It works only for the first element:

json['value'][0]['fields']['System.State']['newValue']

Solution

  • First of all this question is not about parsing json. Second, while iterating inside json["value"]["fields"] such as;

    for i in json['value']:
        for item in i['fields']: 
            print(i['System.State']['newValue']) # error getting raised in this line
    

    There is 4 different dictionaries and only one of them has the ["System.State"] key so when the key is absent, an error is raised. To overcome that you can just add a simple control statement;

    for i in json['value']:
        for item in i['fields']: 
            if 'System.State' in i:
                print(i['System.State']['newValue'])
    

    Edited: After inspected the dict i saw a couple missing brackets. json data can be like;

    {
        "count": 12,
        "value": [
                {
                "id": 1,
                "workItemId": 1,
                "rev": 1,
                "fields": {
                    "System.Id": {
                        "newValue": 1
                    },
                    "System.AreaId": {
                        "newValue": 2
                         },
                     }
                },
                {
                "id": 2,
                "workItemId": 2,
                "rev": 2,
                "fields": {
                    "System.Rev": {
                        "oldValue": 1,
                        "newValue": 2
                    },
                    "System.State": {
                        "oldValue": "New",
                        "newValue": "Qualification"
                    }
                 }
             }
         ]
    }