【问题标题】:Create a new dictionary from a nested JSON output after parsing解析后从嵌套的 JSON 输出创建新字典
【发布时间】:2021-03-28 06:32:27
【问题描述】:

在 python3 中,我需要从 API 调用中获取 JSON 响应, 并解析它,这样我就会得到一个只包含我需要的数据的字典。 我 ecxpt 得到的最终字典如下:

{'Severity Rules': ('cc55c459-eb1a-11e8-9db4-0669bdfa776e', ['cc637182-eb1a-11e8-9db4-0669bdfa776e']), 'auto_collector': ('57e9a4ec-21f7-4e0e-88da-f0f1fda4c9d1', ['0ab2470a-451e-11eb-8856-06364196e782'])}

JSON 响应返回以下输出:

{
    'RuleGroups': [{
        'Id': 'cc55c459-eb1a-11e8-9db4-0669bdfa776e',
        'Name': 'Severity Rules',
        'Order': 1,
        'Enabled': True,
        'Rules': [{
            'Id': 'cc637182-eb1a-11e8-9db4-0669bdfa776e',
            'Name': 'Severity Rule',
            'Description': 'Look for default severity text',
            'Enabled': False,
            'RuleMatchers': None,
            'Rule': '\\b(?P<severity>DEBUG|TRACE|INFO|WARN|ERROR|FATAL|EXCEPTION|[I|i]nfo|[W|w]arn|[E|e]rror|[E|e]xception)\\b',
            'SourceField': 'text',
            'DestinationField': 'text',
            'ReplaceNewVal': '',
            'Type': 'extract',
            'Order': 21520,
            'KeepBlockedLogs': False
        }],
        'Type': 'user'
    }, {
        'Id': '4f6fa7c6-d60f-49cd-8c3d-02dcdff6e54c',
        'Name': 'auto_collector',
        'Order': 4,
        'Enabled': True,
        'Rules': [{
            'Id': '2d6bdc1d-4064-11eb-8856-06364196e782',
            'Name': 'auto_collector',
            'Description': 'DO NOT CHANGE!! Created via API coralogix-blocker tool',
            'Enabled': False,
            'RuleMatchers': None,
            'Rule': 'AUTODISABLED',
            'SourceField': 'subsystemName',
            'DestinationField': 'subsystemName',
            'ReplaceNewVal': '',
            'Type': 'block',
            'Order': 1,
            'KeepBlockedLogs': False
        }],
        'Type': 'user'
    }]
}

我能够创建一个包含名称和 RuleGroupsID 的字典,如下所示:

response = requests.get(url,headers=headers)
output = response.json()
outputlist=(output["RuleGroups"])
groupRuleName = [li['Name'] for li in outputlist]
groupRuleID = [li['Id'] for li in outputlist]
# Create a dictionary of NAME + ID
ruleDic = {}
for key in groupRuleName:
    for value in groupRuleID:
        ruleDic[key] = value
        groupRuleID.remove(value)
        break   

这给了我一本简单的字典:

{'Severity Rules': 'cc55c459-eb1a-11e8-9db4-0669bdfa776e', 'Rewrites': 'ddbaa27e-1747-11e9-9db4-0669bdfa776e', 'Extract': '0cb937b6-2354-d23a-5806-4559b1f1e540', 'auto_collector': '4f6fa7c6-d60f-49cd-8c3d-02dcdff6e54c'} 

但是当我尝试将它解析为嵌套的 JSON 时,事情就不起作用了。

【问题讨论】:

  • 您需要查看响应中json返回的位置,是在response.text中吗?无论如何我都不会将它转换为列表,并在下面循环遍历它的键,输出中的值 .items()

标签: python python-3.x


【解决方案1】:

最后,我设法创建了一个返回该字典的函数, 我通过将 JSON 按所需元素(即第一个嵌套中的 NameIdRules)将 JSON 分成 3 个列表来做到这一点),然后从嵌套的 JSON(列出 Rule 下的所有内容)创建另一个列表,该列表仅从关键字“Id”创建一个列表。

最后在之前创建的列表和字典上使用 zip 命令创建字典。

def get_filtered_rules() -> List[dict]:
    groupRuleName = [li['Name'] for li in outputlist]
    groupRuleID = [li['Id'] for li in outputlist]
    ruleIDList = [li['Rules'] for li in outputlist]
    ruleIDListClean = []
    ruleClean = []
    for sublist in ruleIDList:
        try:
            lstRule = [item['Rule'] for item in sublist]
            ruleClean.append(lstRule)
            ruleContent=list(zip(groupRuleName, ruleClean))
            ruleContentDictionary = dict(ruleContent)
            lstID = [item['Id'] for item in sublist]
            ruleIDListClean.append(lstID)
            # Create a dictionary of NAME + ID + RuleID
            ruleDic = dict(zip(groupRuleName, zip(groupRuleID, ruleIDListClean)))
        except Exception as e: print(e)
    return ruleDic

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2021-06-02
    • 2019-01-18
    • 2015-06-10
    • 2016-06-09
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多