How do I check if a string is valid JSON in Python?

后端 未结 4 1074
南旧
南旧 2020-12-07 10:03

In Python, is there a way to check if a string is valid JSON before trying to parse it?

For example working with things like the Facebook Graph API, sometimes it r

4条回答
  •  半阙折子戏
    2020-12-07 10:28

    I came up with an generic, interesting solution to this problem:

    class SafeInvocator(object):
        def __init__(self, module):
            self._module = module
    
        def _safe(self, func):
            def inner(*args, **kwargs):
                try:
                    return func(*args, **kwargs)
                except:
                    return None
    
            return inner
    
        def __getattr__(self, item):
            obj = getattr(self.module, item)
            return self._safe(obj) if hasattr(obj, '__call__') else obj
    

    and you can use it like so:

    safe_json = SafeInvocator(json)
    text = "{'foo':'bar'}"
    item = safe_json.loads(text)
    if item:
        # do something
    

提交回复
热议问题