Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to summarize a json based on the type of objects it holds?

My input is this 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']}]}

And I’m trying to get this kind of output :

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

My code below gives me: {'str': 8, 'int': 3, 'float': 1}. How can I fix that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))

>Solution :

You can try:

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)

Prints:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading