如何断言JSON响应字段类型为String或int(无需校验字段值)
你提供的JSON样例存在语法错误,标准JSON中数组结构内不能直接书写键值对,正确的结构应为数组包裹对象,形式如下,后续所有校验方案均基于该标准结构实现:
{ "Data": [ { "Id": 1, "Name": "ABC" } ] }
可选校验方案
只校验字段类型、不校验具体值的实现方式很多,根据你使用的技术栈选对应方案即可:
Python接口测试场景(requests+pytest)
直接用Python内置的isinstance方法做类型判断,写法最简单:import requests resp = requests.get("你的接口地址") data = resp.json() first_item = data["Data"][0] # 类型断言,不校验具体值 assert isinstance(first_item["Id"], int) assert isinstance(first_item["Name"], str)Java接口测试场景(RestAssured)
用RestAssured内置的类型匹配器即可,不需要写额外的解析逻辑:import static org.hamcrest.Matchers.isA; import static io.restassured.RestAssured.given; given() .when() .get("你的接口地址") .then() .body("Data[0].Id", isA(Integer.class)) .body("Data[0].Name", isA(String.class));跨技术栈通用方案(JSON Schema)
如果需要做跨语言的统一结构校验,可以编写只约束字段类型、不约束具体值的JSON Schema,所有主流语言都有对应的Schema校验库。匹配你需求的Schema示例如下:{ "type": "object", "required": ["Data"], "properties": { "Data": { "type": "array", "items": { "type": "object", "required": ["Id", "Name"], "properties": { "Id": {"type": "integer"}, "Name": {"type": "string"} } } } } }校验时只要接口返回的结构符合Schema定义就会通过,不会限制Id、Name的具体取值。
前端JavaScript场景
用typeof做基础判断即可,注意JS中没有单独的int类型,所有数字默认都是number类型,需要严格校验整数的话可以加Number.isInteger判断:const resp = await fetch("你的接口地址").then(res => res.json()) const firstItem = resp.Data[0] // 基础类型判断 console.log(typeof firstItem.Id === 'number') // 校验Id为数字 console.log(Number.isInteger(firstItem.Id)) // 严格校验Id为整数 console.log(typeof firstItem.Name === 'string') // 校验Name为字符串
注意:如果
Data数组可能返回多条数据,只需要遍历数组元素,对每个元素重复上述类型校验逻辑即可。
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

