有没有一种简单的方法来检查对象是否在python中是可序列化的?

时间:2017-02-03 21:17:36

标签: python json serialization

我试图检查对象是否是JSON可序列化的,因为我有一个包含大量内容的字典,此时它更容易遍历其键并查找它们是否是JSON可序列化并删除它们。类似的东西(虽然这会检查它的功能):

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

有没有办法让if语句检查JSON可序列化对象并以类似的方式从字典中删除它们?

2 个答案:

答案 0 :(得分:21)

比宽容更容易请求宽恕

def notify_admin (message_details)
    @message_details = message_details
    mail(to: "jesse@mydomain.com", subject: "Contact form filled out by: " + message_details[:name], from: message_details[:email])
end

然后在你的代码中:

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

答案 1 :(得分:8)

@ shx2的答案足够好,但是最好指定要捕获的异常。

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

当x包含一个对于JSON而言无法编码的数字时,将引发OverflowError。可以找到相关的答案here

相关问题