【问题标题】:Extract list item from nested json/dictionary in python从python中的嵌套json/字典中提取列表项
【发布时间】:2020-12-14 19:39:46
【问题描述】:

我在 python 中有一个如下所示的 json:

{
  "Id": "123",
  "fields": {
    "List1": [{
        "List2": [
          {
            "List3": [
              { "item":"1",
                "Activation": False
                },
              { "item":"2",
                "Activation":True
               },
              { "item":"3",
                "Activation":False
               },               
]}]}]}}

如何编写一个返回 Activation:False 计数的函数? 所以在这个例子中,它将返回 2,因为有两个项目具有 Activation:False。

类似:

def count_false:
    #code to count false
    return count

提前致谢!

【问题讨论】:

  • 这只是一系列列表和字典查找以及一个循环。当您尝试这样做时是否遇到了特殊问题?

标签: python json list dictionary


【解决方案1】:

此函数将递归查找密钥“激活”并返回错误激活的数量。

def count_false(your_obj):
    count = 0
    if isinstance(your_obj, dict):
        for k, v in your_obj.items():
            if k == 'Activation':
                count += 1 if v is False else 0
            elif isinstance(v, list):
                for e in v:
                    count += count_false(e)
            elif isinstance(v, dict):
                count += count_false(v)
    return count

你也可以用正则表达式解决这个问题:

import re
import json

def count_false(your_obj):
    json_string = json.dumps(your_obj)
    matches = re.findall(r'"Activation": false\b', json_string)
    return len(matches)

【讨论】:

    【解决方案2】:

    试试下面的

    data = {
        "Id": "123",
        "fields": {
            "List1": [{
                "List2": [
                    {
                        "List3": [
                            {"item": "1",
                             "Activation": False
                             },
                            {"item": "2",
                             "Activation": True
                             },
                            {"item": "3",
                             "Activation": False
                             },
                        ]}]}]}}
    
    num_of_false_activation = sum(1 for x in data['fields']['List1'][0]['List2'][0]['List3'] if x['Activation'] is False)
    print(num_of_false_activation)
    

    输出

    2
    

    【讨论】:

    • 如何处理“TypeError:字符串索引必须是整数”错误
    • 这个问题没有一般的答案。你在运行我的代码时得到它了吗?
    • 当我尝试在 pyspark 中将其用作 udf 时出现错误。可能涉及其他问题。感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多