skip to Main Content

I have the following json:

[
    {
        "id": 1,
        "category": {
            "id": 0,
            "nombre": "string"
        },
        "nombre": "Julian"
    },
    {
        "id": 2,
        "category": {
            "id": 0,
            "nombre": "string"
        },
        "nombre": "Pedro"
    },
{
        "id": 3,
        "category": {
            "id": 0,
            "nombre": "string"
        },
        "nombre": "Julian"
    },
{
        "id": 4,
        "category": {
            "id": 0,
            "nombre": "string"
        },
        "nombre": "Pedro"
    },
{
        "id": 5,
        "category": {
            "id": 0,
            "nombre": "string"
        },
        "nombre": "Maria"
    }
]

And I have the following python class:

import json

id = 0
nombre = ""

class Persona(object):
    def __init__(self, id, nombre):
        self.id = id
        self.nombre = nombre

def cargaDeDatos(ruta):
    with open(ruta) as contenido:
        mascotasVendidas = json.load(contenido)

if __name__ == '__main__':
    ruta = 'data/archivo.json' 
    cargaDeDatos(ruta)

What I would like to know is how to save in a python class the data of the people (id and name) that are in the .json file.

I need to create a function that brings me the repeated names

2

Answers


  1. Here’s how you can modify your code to achieve this:

    import json
    
    class Persona:
        def __init__(self, id, nombre):
            self.id = id
            self.nombre = nombre
    
    def cargaDeDatos(ruta):
        with open(ruta) as contenido:
            mascotasVendidas = json.load(contenido)
        personas = []
        for item in mascotasVendidas:
            id = item['id']
            nombre = item['nombre']
            persona = Persona(id, nombre)
            personas.append(persona)
        return personas
    
    def find_repeated_names(personas):
        name_counts = {}
        repeated_names = []
        for persona in personas:
            if persona.nombre in name_counts:
                name_counts[persona.nombre] += 1
            else:
                name_counts[persona.nombre] = 1
            if name_counts[persona.nombre] == 2:
                repeated_names.append(persona.nombre)
        return repeated_names
    
    if __name__ == '__main__':
        ruta = 'data/archivo.json' 
        personas = cargaDeDatos(ruta)
        
        repeated_names = find_repeated_names(personas)
        print("Repeated Names:", repeated_names)
    
    Login or Signup to reply.
  2. You can use dataclasses and a counter here.

    from collections import Counter
    from dataclasses import dataclass
    from json import loads
    
    
    @dataclass
    class Person:
        id: int
        name: str
    
        # some of the following type annotations require a
        # recent python version, if you get errors, delete them
        
        @classmethod
        def from_json(cls, json_data: str) -> list['Person']:
            data = loads(json_data)
            people = []
            for entry in data:
                # you might want to access different keys here,
                # depends on structure, adjust accordingly
                entry_id = entry['id']
                entry_name = entry['nombre']
                people.append(cls(entry_id, entry_name))
            return people
    
        @staticmethod
        def count_occurrences(people: list['Person']) -> Counter:
            return Counter([person.name for person in people])
    
    
    # use like this
    people = Person.from_json("""
    [
        {
            "id": 1,
            "category": {
                "id": 0,
                "nombre": "string"
            },
            "nombre": "Julian"
        },
        {
            "id": 2,
            "category": {
                "id": 0,
                "nombre": "string"
            },
            "nombre": "Pedro"
        },
        {
            "id": 3,
            "category": {
                "id": 0,
                "nombre": "string"
            },
            "nombre": "Julian"
        }
    ]
    """)
    
    print(people)
    print(Person.count_occurrences(people))
    
    # get repeated names like so:
    repeated = [name for name, count in Person.count_occurrences(people).items() if count > 1]
    print(repeated)
    

    A library you should check out, if you need to work with JSON more often, and especially when generating objects from it is pydantic

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search