如何在Python中检查字符串是否为有效的JSON? [英] How do I check if a string is valid JSON in Python?

查看:389
本文介绍了如何在Python中检查字符串是否为有效的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,有没有办法在尝试解析字符串之前检查字符串是否为有效JSON?

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

例如,使用诸如Facebook Graph API之类的东西时,有时返回JSON,有时可能返回图像文件.

For example working with things like the Facebook Graph API, sometimes it returns JSON, sometimes it could return an image file.

推荐答案

您可以尝试执行json.loads(),如果您传递的字符串不能被解码为JSON,则会抛出ValueError.

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

通常,针对这种情况的" Pythonic "哲学这种情况称为 EAFP ,因为权限.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

这篇关于如何在Python中检查字符串是否为有效的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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