首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JSON响应中导航以捕获值

在JSON响应中导航以捕获值
EN

Stack Overflow用户
提问于 2022-04-08 23:32:58
回答 1查看 41关注 0票数 1

我试图在"Tags“键下的"process:ilapd”值中捕获"ilapd“字符串,但没有成功。我怎么才能抓住这根绳子?

我尝试用for循环中的几个变量来迭代数据,但是对于类型整数,我一直在获取错误。

JSON数据如下:

代码语言:javascript
复制
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"
      }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-08 23:37:20

您可以使用str.split + str.startswith

代码语言:javascript
复制
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)

指纹:

代码语言:javascript
复制
ilapd

或者使用re模块:

代码语言:javascript
复制
import re

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

for t in data["Tags"].split(","):
    if (m := r.search(t)) :
        print(m.group(1))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71804073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档