【问题标题】:How to fix unexpected end of json error when i run JSON.parse()运行 JSON.parse() 时如何解决意外的 json 错误结束
【发布时间】:2021-11-18 09:54:37
【问题描述】:

我正在做一个文件验证项目。 当文档存在或登录的人发布文档时,我的代码有效。 但是当文档不是由登录的人发布时(例如对于新用户),它会失败并返回“JSON 意外结束”错误。 当我在 Ejs 上使用 JSON.parse(documents) 时返回错误。 如何在 EJS 中使用 try-catch 或任何其他方式捕获错误? 这是找到文档时的代码结果(预期输出)

<% console.log('fit', JSON.parse(documents, null, '\t')) %>

Output
fit [ { Key: 'DOCUMENT0', Record: { name: 'bachelor of science degree', url: 'https://bitcoin.org/ggg.pdf', issuedBy: 'sol123', dateOfIssuance: '12:18 PM, 25 September, 2021', hashedDoc: 'dac729a8acf4b8a88f73f5bd84206c34e01e0992efa251b772f68696e2c2539c9ed0090e73ef6b87dc24e3177c6fd5341c3e9e24ef14267ce07ab9428aeed897', docType: 'Whitepaper' } } ]

问题是找不到文档时(例如,如果用户是新用户且尚未发布文档);

SyntaxError: /home/verification/fabcar/javascript/views/pages/dashboard.ejs:15
    13|     <div class="list-group" id="list-tab" role="tablist" style="margin-top: 10px;">
    14| 
 >> 15|     <% JSON.parse(documents).forEach(document => { %>
    16|         <a class="list-group-item list-group-item-action" id="<%= document.Key %>" data-bs-toggle="tab"
    17|           href="#list-<%= document.Key %>" role="tab" aria-controls="list-<%= document.Key %>" style="min-width: 200px;"><%= document.Key %></a>
    18|     <% }) %>

Unexpected end of JSON input
    at JSON.parse (<anonymous>

我想要的是, 当用户没有发布文档时,如何在 EJS 上显示NO DOCUMENT ISSUED 消息。我需要你的帮助我是 javaScript 和 ejs 的新手。

【问题讨论】:

    标签: javascript ejs fabricjs


    【解决方案1】:

    你可以使用try catch

    try {
    
      let user = JSON.parse(json); 
    
    } catch (err) {
      
      alert( "user is new and not yet issued document" );
      console.log( err.name );
      console.log( err.message );
    }
    

    通过这样做,您可以验证每个错误并做出相应的响应。

    或者使用验证真假功能,如下所示并相应地继续

    function isValidJSON(text) {
      try {
        JSON.parse(text);
        return true;
      } catch {
        return false;
      }
    }
    

    更新了问题:如何在 ejs 中创建 try catch

    这里是 try catch 的例子

    <%
    
    function isValidJSON(text) {
      try {
        JSON.parse(text);
        return true;
      } catch {
        return false;
      }
    }
    var json1 = '{"item" : {"item2" : "item Data"}}';
    var json2 = '{"item" : {"item2" : "item Data}}';
    
    %>
    
    
    
    pasing json 
    <% if(isValidJSON(json1))  { %>
    <p>Valid jsonr!</p>
    <% } else { %>
    <p>Invalid Json!</p>
    
    <% } %>
    
    pasing json 
    <% if(isValidJSON(json2))  { %>
    <p>Valid jsonr!</p>
    <% } else { %>
    <p>Invalid Json!</p>
    
    <% } %>
    

    可以看到json1有效,json2无效。

    【讨论】:

    • 感谢您的回答 c,但是我如何在 ejs 中创建 try catch 或在 ejs 中创建函数?
    • 它是java脚本而不是C,并且更新了代码ejs代码
    • 谢谢库马拉。
    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多