json格式校验
- 非严格模式
json.loads(data, strict=False)
如果strict为false(默认值为True),则字符串中允许使用控制字符。此上下文中的控制字符是那些字符代码在0–31范围内的字符,包括“\t”(制表符)、“\n”、“r”和“\0”。
代码实例
import json
def check_json(json_file) -> bool:
try:
# rb方式打开可以去除非utf-8编码产生的错误
with open(json_file, 'rb') as f:
json.loads(f.read(), strict=False)
return True
except Exception as e:
print(f"JSON format verification failed: {e}")
return False
xml格式校验
代码实例
from xml.etree import ElementTree as ET
def check_xml(xml_file: str) -> bool:
try:
with open(xml_file, "r") as f:
ET.fromstring(f.read())
return True
except Exception as e:
print(f"JSON format verification failed: {e}")
return False