You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:24:02