如何判断返回的python字符串是否符合json格式

简介: 如何判断返回的python字符串是否符合json格式
def is_json(msg):
    # 首先判断是否是字符串
    if isinstance(msg, str):
        # 在这里先判断是否为数字类型的数据
        try:
            isinstance(int(msg), int)
            return ("这个不是json类型数据")
        except:
            pass
        try:
            # 其次进行转换成python自带的数据类型
            json.loads(msg)
            return ("这个是json类型数据")
        except ValueError:
            return ("这个不是json类型数据")
    else:
        return ("这个不是json类型数据")

上面代码中为什么要先判断返回的字符串是否可以转为int类型的呢?

因为实践证明“123”这种也是可以通过上面的校验的(如下图)

所以要针对这块进行优化下

 

相关文章
|
9天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
191 100
|
9天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
206 99
|
12天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
12天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
12天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
23天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
213 92
|
2月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
187 0
|
2月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多