Home > Net >  Unable to extract required field from JSON text
Unable to extract required field from JSON text

Time:04-06

I am trying to extract a specific field "Engineering Lead" and its corresponding value from the JSON text but however, when tried to extract it directly from the JSON, it is throwing the key error as shown in the code1 . Since it is not working, i have decided to loop it to fetch the key Engineering Lead and it is value but it still throwing the same error. any help would be aprreciated.

json text:

{'expand': 'renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations', 'id': '11659640', 'self': '/rest/api/2/issue/11659640', 'key': 'TOOLSTEST-2651', 'fields': {'description': 'h2. Main\r\n * *:*\r\n * *Application ISO:*\xa0Tony Zeinoun\r\n * *Engineering Lead:*\xa0Peter james\r\n * *Application Architect:*\xa0John david\r\n * *Divisional Architect:*\xa0Robert denuvit'}}

code 1:

 engLeadDetails = data_load['fields']['* \*Engineering Lead']
  

Code 2:

engLeadDetails = data_load['fields']
    for k,v in engLeadDetails.items():
        if (k == '* \*Engineering Lead'):
            print (v)

Error:

Traceback (most recent call last):
  File "/Users/peter/abc.py", line 32, in <module>
    engLeadDetails = data_load['fields']['* *Engineering Lead']
KeyError: '* *Engineering Lead'

CodePudding user response:

I think python can't find such key because of some missing quotes. Please check the json text once more. It seems like * *Engineering Lead is currently a part of a bigger string, but not a key (due to missing quotes).

CodePudding user response:

You can convert youe JSON string description into a dictionary by splitting on \r\n sequence then break the role and name into key/values and add to a dictionary.

Try something like this:

data = {}
for s in data_load['fields']['description'].split('\r\n'):
   if m := re.search(r'^(?: \* \*)?(.*?):\*?(. )', s):
      label = m.group(1)
      if label != '':
         data[label] = m.group(2)
print(data)

Output:

{'Application ISO': '\xa0Tony Zeinoun', 'Engineering Lead': '\xa0Peter james', 'Application Architect': '\xa0John david', 'Divisional Architect': '\xa0Robert denuvit'}

Then can grab a particular role/person out:

print(">>", data.get("Engineering Lead"))

Outputs:

>> Peter james
  • Related