如何根据json包含的对象类型来总结json?

qhhrdooz  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(87)

我的输入是json:

object = {'name': 'John',
 'age': 30,
 'address': {'street': '123 Main St',
  'city': 'Sampletown',
  'zipcode': '12345',
  'frequency': 12.55},
 'interests': ['Python programming',
  {'hobbies': ['Playing chess',
    {'outdoor': {'activity1': 'Hiking', 'activity2': 'Cycling'}}]}],
 'friends': [{'name': 'Alice', 'age': 28},
  {'name': 'Bob', 'age': 32, 'hobbies': ['Hiking', 'Reading']}]}

我试着得到这样的输出:

{"str": 30, "dict": 6, "list": 4, "int": 3, "float": 1}

下面的代码给我:{'str': 8, 'int': 3, 'float': 1} .我该怎么解决这个问题?

from collections import Counter

def get_the_type(o):
    for key,val in o.items():
        if not isinstance(val, (list, dict)):
            yield type(val).__name__
        elif isinstance(val, list):
            for v in val:
                if isinstance(v, dict):
                    yield from get_the_type(v)
        else:
            yield from get_the_type(val)

final_dict = dict(Counter(get_the_type(object)))
uinbv5nw

uinbv5nw1#

您可以尝试:

obj = {
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Sampletown",
        "zipcode": "12345",
        "frequency": 12.55,
    },
    "interests": [
        "Python programming",
        {
            "hobbies": [
                "Playing chess",
                {"outdoor": {"activity1": "Hiking", "activity2": "Cycling"}},
            ]
        },
    ],
    "friends": [
        {"name": "Alice", "age": 28},
        {"name": "Bob", "age": 32, "hobbies": ["Hiking", "Reading"]},
    ],
}

from collections import Counter

def count(o):
    yield type(o).__name__

    if isinstance(o, dict):
        for k, v in o.items():
            yield type(k).__name__
            yield from count(v)
    elif isinstance(o, (list, tuple)):
        for v in o:
            yield from count(v)

c = Counter(count(obj))

# exclude type of the whole object (optional):
# c[type(obj).__name__] -= 1

print(c)

图纸:

Counter({'str': 30, 'dict': 7, 'list': 4, 'int': 3, 'float': 1})

相关问题