45

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?

2
  • 1
    Put a try/catch around a call to json.dumps(). Commented Feb 3, 2017 at 21:18
  • 1
    Took a look at the source code. json.dump uses JSONEncoder.encode by default. But its encoding (serializing) is rather hard-coded. Basically it's impossible to check without giving it a try. Commented Feb 27, 2024 at 8:20

2 Answers 2

69

@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.

Sign up to request clarification or add additional context in comments.

Comments

35

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)

5 Comments

that is hilariously smart, +1 for creativity for sure.
It's normally bad practice to catch all exception like that, it may masks bugs, either in the json implementation or in encoder hooks if you have any. @R. Yangs answer is better
This is a terrible example for the statement 'Easier to Ask Forgiveness than Permission.'.
Don't use a wide 'except' like that as it catches KeyboardInterrupt errors too and makes your program unexitable from inside that try block.
This can be a very bad idea if your object happens to be serializable and occupies a few gigabytes of swap memory. Could take you the whole afternoon to find out if the object is serializable...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.