【问题标题】:How do you select all strings in between certain substrings in python and create a csv out of the results?如何在 python 中的某些子字符串之间选择所有字符串并从结果中创建一个 csv?
【发布时间】:2018-06-29 18:38:51
【问题描述】:

我正在尝试在 python 中解析 A​​PI 调用的结果。

{'data': [{'type': 'infra_process_running', 'name': 'Custom Plugin Alert - Stopped Running', 'enabled': True, 'filter': {'and': [{'is': {'entityName': 'SOMEHOSTNAME','SOMEHOSTNAME'}}]}, 'id': 123456, 'created_at_epoch_millis': 1513024072143, 'updated_at_epoch_millis': 1513024072176, 'policy_id': 127350, 'comparison': 'below', 'critical_threshold': {'value': 2, 'duration_minutes': 5}, 'process_filter': {'and': [{'is': {'commandLine': 'java'}}]}}], 'meta': {'limit': 50, 'offset': 0, 'total': 1}, 'links': {}}

编辑:抱歉忘了说这是在 python 中对请求运行 print 的输出,这就是为什么它是单引号而不是像 JSON 那样双引号

我想从此请求中提取所有“名称”和所有“实体名称”。 我尝试使用正则表达式搜索并将它们存储在列表中

list.append(re.search(r"', 'name': '(.*?)', '", stringInfJSON))
list.append(re.search(r"{'entityName': ['(.*?)']", stringInfJSON))

我想从此请求中提取所有“名称”和所有“实体名称”。

然后我想以以下格式将所有这些插入到 Excel 电子表格中

+---------------------------------------+---------------------+
| Somehostname(s)                       | Somehostname2       |
+---------------------------------------+---------------------+
| Custom Plugin Alert - Stopped Running | Blah Blah Blah Blah |
+---------------------------------------+---------------------+

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: python json regex csv python-requests


【解决方案1】:

假设您正在获取 JSON 格式的 API 响应,您应该能够使用

my_dict = json.load([JSON variable])
for x in my_dict['data']:
     list.append(x['name'])

第一行会将 JSON 转换为 python dict,然后你需要循环它,因为 JSON 包含一个数组,其中的每个元素大概都有一个 name 值。你需要在 python 文件中import json

我不建议您尝试为此使用正则表达式;没有理由将 JSON 响应转换为字符串。

要获取实体名称,可以使用相同的方法:

for x in my_dict['data']:
      for y in x['filter']['and']:
             list.append(y['is']['entityName']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2013-12-31
    • 2020-03-27
    • 2019-12-20
    • 2011-11-13
    相关资源
    最近更新 更多