Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
Is there an easy way to check if an object is JSON serializable in python?

I was trying to check if objects were JSON serializable or not because I had a dictionary that had a bunch of things and at this point its just easier to loop through its keys and find if they are JSON serializable and remove them. Something like (though this checks if its function):

def remove_functions_from_dict(arg_dict):
    '''
        Removes functions from dictionary and returns modified dictionary
    '''
    keys_to_delete = []
    for key,value in arg_dict.items():
        if hasattr(value, '__call__'):
            keys_to_delete.append(key)
    for key in keys_to_delete:
        del arg_dict[key]
    return arg_dict

is there a way that the if statement instead check for JSON serializable objects and deletes them from the dictionary in a similar way to above?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

@shx2's answer is good enough, but it's better to specify which exceptions you're catching.

def is_jsonable(x):
    try:
        json.dumps(x)
        return True
    except (TypeError, OverflowError):
        return False

OverflowError is thrown when x contains a number which is too large for JSON to encode. A related answer can be found here.

over 4 years ago · Santiago Trujillo Relatório

0

Easier to Ask Forgiveness than Permission.

import json
def is_jsonable(x):
    try:
        json.dumps(x)
        return True
    except:
        return False

Then in your code:

for key,value in arg_dict.items():
    if not is_jsonable(value):
        keys_to_delete.append(key)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda