如何无需遍历JSON对象,验证API响应包含指定键?
需求说明
我期望API端点返回的JSON对象需包含id、name、Body键,示例对象如下:
let ExampleObject={ "id":"", "name":"", "Body":"" }
现需验证API响应的JSON对象(非数组)包含上述键,但不想通过遍历实现,该如何操作?
现有代码
错误处理函数及请求函数
function handleError(err) { //handling error code based return err } export const GetUsers = async({ user, Following }, Paging) => { try { const response = await fetch(Apiurl, { method: 'GET', withCredentials: true, credentials: 'include', headers: { 'Authorization': Token, 'Content-Type': 'application/json' } }) if (response.status != 200) { throw ('Error Sending request') } const ResponseArray = await response.json(); //Verify object here if ('Key') { throw ('error with json') } return ResponseArray } catch (err) { throw (handleError(err)) }; };
调用请求函数的代码
async function callapi() { try { await GetUsers(Object, Paging) } catch (err) { } }
解决方案
不用遍历的话,直接通过逻辑运算符结合键存在性检查,就能一次性验证所有必填字段,以下是两种可行方案:
方案1:直接检查键的存在性
利用in运算符判断键是否存在于对象中,结合&&逻辑与确保所有必填键都存在,同时先校验返回值是否为非数组对象:
const responseData = await response.json(); // 先校验返回的是合法的非数组对象 if (typeof responseData !== 'object' || responseData === null || Array.isArray(responseData)) { throw ('API返回格式错误,预期为非数组对象'); } // 验证所有必填键是否存在 if (!( 'id' in responseData && 'name' in responseData && 'Body' in responseData )) { throw ('返回的JSON对象缺少id、name或Body键'); }
方案2:使用hasOwnProperty校验自有属性
如果需要排除对象继承来的属性,确保键是对象自身拥有的,可以用hasOwnProperty:
if (!(responseData.hasOwnProperty('id') && responseData.hasOwnProperty('name') && responseData.hasOwnProperty('Body'))) { throw ('返回的JSON对象缺少必填的自有属性键'); }
整合后的完整请求函数
把验证逻辑嵌入你的代码,修改后的GetUsers函数如下:
function handleError(err) { // 可补充具体错误处理逻辑 return err } export const GetUsers = async({ user, Following }, Paging) => { try { const response = await fetch(Apiurl, { method: 'GET', withCredentials: true, credentials: 'include', headers: { 'Authorization': Token, 'Content-Type': 'application/json' } }) if (response.status !== 200) { throw ('请求发送失败'); } const responseData = await response.json(); // 校验返回格式是否为非数组对象 if (typeof responseData !== 'object' || responseData === null || Array.isArray(responseData)) { throw ('API返回格式错误,预期为非数组对象'); } // 验证所有必填键存在 if (!( 'id' in responseData && 'name' in responseData && 'Body' in responseData )) { throw ('返回的JSON对象缺少id、name或Body键'); } return responseData } catch (err) { throw handleError(err); }; };
内容的提问来源于stack exchange,提问作者Abd
相关产品推荐
相关产品推荐

