如何在Python中检查一个字符串是否是有效的JSON?

2wnc66cl  于 2023-02-26  发布在  Python
关注(0)|答案(6)|浏览(178)

在Python中,有没有办法在解析字符串之前检查它是否是有效的JSON?
例如,使用Facebook图形API之类的东西,有时它会返回JSON,有时它会返回图像文件。

ekqde3dh

ekqde3dh1#

可以尝试执行json.loads(),如果传递的字符串不能解码为JSON,则将抛出ValueError
一般来说,这种情况下的“Python”哲学被称为EAFP,意思是“请求原谅比请求许可容易”。

sqxo8psd

sqxo8psd2#

示例Python脚本在字符串为有效json时返回布尔值:

import json

def is_json(myjson):
  try:
    json.loads(myjson)
  except ValueError as e:
    return False
  return True

其中打印:

print is_json("{}")                          #prints True
print is_json("{asdf}")                      #prints False
print is_json('{ "age":100}')                #prints True
print is_json("{'age':100 }")                #prints False
print is_json("{\"age\":100 }")              #prints True
print is_json('{"age":100 }')                #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
    • 将JSON字符串转换为Python字典:**
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo'])    #prints bar

mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
    • 将python对象转换为JSON字符串:**
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo))           #prints {"gummy": "bear"}

如果你想访问低级解析,不要使用自己的库,使用现有的库:http://www.json.org/
关于python JSON模块的优秀教程:https://pymotw.com/2/json/

是字符串JSON并显示语法错误和错误消息:

sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json

图纸:

, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.

json_xs能够进行语法检查、解析、打印、编码、解码等:
https://metacpan.org/pod/json_xs

4nkexdtk

4nkexdtk3#

我想说解析是你能真正完全分辨的唯一方法。如果格式不正确,python的json.loads()函数(几乎可以肯定)会引发异常。然而,你的例子的目的可能只是检查前几个非空格字符...
我对facebook返回的JSON不太熟悉,但是大多数来自web应用的JSON字符串都是以[{的方括号开头的,据我所知,没有任何图像格式是以这些字符开头的。
相反,如果您知道可能显示哪些图像格式,则可以检查字符串的开头以查找它们的签名来识别图像,如果不是图像,则假设使用的是JSON。
另一个识别图形而不是文本字符串的简单方法是,在您查找图形的情况下,测试字符串的前几十个字符中是否有非ASCII字符(假设JSON是ASCII)。

n3ipq98p

n3ipq98p4#

对于这个问题,我想出了一个通用的、有趣的解决方案:

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

你可以这样使用它:

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

knpiaxh15#

一种有效、可靠的方法来检查有效的JSON。如果'get'访问器不抛出AttributeError,则JSON是有效的。

import json

valid_json =  {'type': 'doc', 'version': 1, 'content': [{'type': 'paragraph', 'content': [{'text': 'Request for widget', 'type': 'text'}]}]}
invalid_json = 'opo'

def check_json(p, attr):
    doc = json.loads(json.dumps(p))
    try:
        doc.get(attr) # we don't care if the value exists. Only that 'get()' is accessible
        return True
    except AttributeError:
        return False

要使用,我们调用函数并查找键。

# Valid JSON
print(check_json(valid_json, 'type'))

返回“True”

# Invalid JSON / Key not found
print(check_json(invalid_json, 'type'))

返回“False”

hgb9j2n6

hgb9j2n66#

在try块中非常简单。然后可以验证主体是否是有效的JSON

async def get_body(request: Request):
try:
    body = await request.json()
except:
    body = await request.body()
return body

相关问题