如何用Python检测字符串是否为有效的JSON格式?
- 内容介绍
- 文章标签
- 相关推荐
本文共计208个文字,预计阅读时间需要1分钟。
Json介绍+全名JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端通信的数据格式。现在也常用于http请求中,因此对json的各种学习都是必要的。
Json介绍
全名JavaScript Object Notation,是一种轻量级的数据交换格式。
Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。
示例代码如下
# -*- coding=utf-8 -*-import json
def check_json_format(raw_msg):
"""
用于判断一个字符串是否符合Json格式
"""
if isinstance(raw_msg, str): # 首先判断变量是否为字符串
try:
json.loads(raw_msg, encoding='utf-8')
except ValueError:
return False
return True
else:
return False
if __name__ == "__main__":
print(check_json_format("""{"a":1}"""))
print(check_json_format("""{'a':1}"""))
print(check_json_format({'a': 1}))
print(check_json_format(100))
去期待陌生,去拥抱惊喜。
本文共计208个文字,预计阅读时间需要1分钟。
Json介绍+全名JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端通信的数据格式。现在也常用于http请求中,因此对json的各种学习都是必要的。
Json介绍
全名JavaScript Object Notation,是一种轻量级的数据交换格式。
Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。
示例代码如下
# -*- coding=utf-8 -*-import json
def check_json_format(raw_msg):
"""
用于判断一个字符串是否符合Json格式
"""
if isinstance(raw_msg, str): # 首先判断变量是否为字符串
try:
json.loads(raw_msg, encoding='utf-8')
except ValueError:
return False
return True
else:
return False
if __name__ == "__main__":
print(check_json_format("""{"a":1}"""))
print(check_json_format("""{'a':1}"""))
print(check_json_format({'a': 1}))
print(check_json_format(100))
去期待陌生,去拥抱惊喜。

