Home > database >  Navigating through a JSON Response to capture a value
Navigating through a JSON Response to capture a value

Time:04-10

I am trying to capture the "ilapd" string in the "process:ilapd" value under the "Tags" key but have not been successful. How do I go about grabbing this string?

I have tried to iterate through the data with several variables of a for loop but keep getting errors for type integers.

JSON data below:

data = {
   "alertOwner":"team",
   "assignGroup":"team",
   "component":"lnx2",
   "Tags":"application:unknown, appowner:secops, bgs:performance, businessgroup:top, drexercise:no, env:nonprod, facility:hq, host:lnx2, location:somewhere, manager:smith, monitor, monitoring24x7:yes, osowner:unix, process:ilapd",
   "description":"Process ilapd is not running on lnx2, expected state is running,",
   "Event Url":"https://app.datadoghq.com/monitors#67856691",
   "logicalName":"lnx2",
   "Metric Graph":"<img src=\"\" />",
   "pageGroups":"team",
   "priority":"4",
   "Snapshot Link":"",
   "type":"test"
      }

CodePudding user response:

You can use str.split str.startswith:

data = {
    "alertOwner": "team",
    "assignGroup": "team",
    "component": "lnx2",
    "Tags": "application:unknown, appowner:secops, bgs:performance, businessgroup:top, drexercise:no, env:nonprod, facility:hq, host:lnx2, location:somewhere, manager:smith, monitor, monitoring24x7:yes, osowner:unix, process:ilapd",
    "description": "Process ilapd is not running on lnx2, expected state is running,",
    "Event Url": "https://app.datadoghq.com/monitors#67856691",
    "logicalName": "lnx2",
    "Metric Graph": '<img src="" />',
    "pageGroups": "team",
    "priority": "4",
    "Snapshot Link": "",
    "type": "test",
}

process = next(
    tag.split(":")[-1]
    for tag in map(str.strip, data["Tags"].split(","))
    if tag.startswith("process:")
)

print(process)

Prints:

ilapd

Or using re module:

import re

r = re.compile(r"process:(.*)")

for t in data["Tags"].split(","):
    if (m := r.search(t)) :
        print(m.group(1))
  • Related