get exact value of elements from json body

I am looking to extract specific values from json objects. Please see the json body below.

json

 data.json = [
   {
      "id": 1,
      "modifiedBy": "admin",
      "fields": {
        "Application": "1",
        "Endtermin": 23011990
        }
      },
      {
      "id": 2,
      "modifiedBy": "admin",
      "fields": {
        "Application": "2",
        "Endtermin": 11021990
        }
      }
      ]

I want to print only ‘Application’ from the list in a table form where table consists of one row and two columns.

Application = 1, 2

I tried in python, but getting error. ‘TypeError: list indices must be integers or slices, not str’

Python

 import json
 import sys
 data = [
   {
      "id": 1,
      "modifiedBy": "admin",
      "fields": {
        "Application": "1",
        "Endtermin": 23011990
        }
      },
      {
      "id": 2,
      "modifiedBy": "admin",
      "fields": {
        "Application": "2",
        "Endtermin": 11021990
        }
      }
      ]

 json_str = json.dumps(data)

 resp = json.loads(json_str)

 print (resp)

 print (resp['Application'])

Answer

Since, data is already a dictionary object, you don’t need json and can simply use list comprehension as:

apps = [elt["fields"]["Application"] for elt in data] # Output ['1', '2']

You could also use get() in case the keys are missing for some elements in the list:

apps = [elt.get("fields",{}).get("Application") for elt in data] # Output ['1', '2']

Leave a Reply

Your email address will not be published. Required fields are marked *