有没有一种简单的方法来检查对象是否可在python中以JSON序列化? [英] Is there an easy way to check if an object is JSON serializable in python?

查看:330
本文介绍了有没有一种简单的方法来检查对象是否可在python中以JSON序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检查对象是否可序列化为JSON,因为我有一本字典,里面有一堆东西,这时更容易遍历其键,查找它们是否可序列化并删除.类似的东西(尽管这会检查其功能):

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

是否可以使用if语句来检查JSON可序列化对象,并以与上述类似的方式将其从字典中删除?

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?

推荐答案

比许可权更容易获得宽恕.

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

然后在您的代码中:

for key,value in arg_dict.items():
    if not is_jsonable(value):
        keys_to_delete.append(key)

这篇关于有没有一种简单的方法来检查对象是否可在python中以JSON序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆