EJS中如何校验JSON.parse输入合法性,无签发文档时展示提示
解决方案
你可以通过异常捕获+空值判断的逻辑兼容两种场景,避免JSON解析错误,完整EJS代码如下:
<% let docList = [] try { // 先把Buffer转成字符串,再做JSON解析 const docStr = typeof documents === 'string' ? documents : documents.toString('utf8') if (docStr.trim()) { docList = JSON.parse(docStr) } } catch (e) { // 解析失败说明无有效文档,保持docList为空数组即可 } %> <% if (docList.length > 0) { %> <% docList.forEach(document => { %> <a class="list-group-item list-group-item-action" id="<%= document.Key %>" data-bs-toggle="tab" href="#list-<%= document.Key %>" role="tab" aria-controls="list-<%= document.Key %>" style="min-width: 200px;"><%= document.Key %></a> <% }) %> <% } else { %> <p class="text-muted">无已签发文档</p> <% } %>
逻辑说明
- 优先判断
documents类型,如果是Buffer就先转成UTF-8字符串,避免直接传入JSON.parse触发格式错误 - 用
try catch包裹解析逻辑,不管是空字符串、非法JSON还是其他异常格式,都会默认返回空数组,不会打断页面渲染 - 最后通过解析后的数组长度判断展示内容,有数据时循环渲染文档列表,无数据时展示提示文本
内容的提问来源于stack exchange,提问作者fit
相关产品推荐
相关产品推荐

