zoukankan      html  css  js  c++  java
  • JSON.parse() 报错和一些解决方法

    js 报错 Unexpected end of JSON input,Unexpected token u in JSON at position 0

    JSON 通常用于与服务端交换数据。

    在接收服务器数据时一般是字符串。

    我们可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

    在谷歌浏览器的 Console 调试台中尝试一下这几种参数的返回结果:

    JSON.parse(null);
    // null
    
    JSON.parse("");
    // VM6600:1 Uncaught SyntaxError: Unexpected end of JSON input
    
    JSON.parse(undefined);
    // VM6635:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

    可以发现 JSON.parse() 的参数必须符合 JSON字符串 的格式才可以被正确的转换为对象,否则可能会引起报错,从而对其它的代码造成影响。

    当我们不能确定服务端返回的数据类型时,这几个例子就可以用上了:

    // 判断数据是否存在
    var str = str && JSON.parse(str) || {};
    
    // 判断数据类型
    var str = typeof str == "string" ? JSON.parse(str) : {};
    
    // 通过 try catch 捕捉异常,防止代码报错
    var c = null;
    try {
        c = JSON.parse(str)
    } catch (d) {}

    同理 JSON.stringify

    var g = "";
    try {
        g = JSON.stringify(a)
    } catch (u) {}
    
    "object" == typeof a ? JSON.stringify(a) : a
  • 相关阅读:
    LibreOJ2095
    Codeforces
    LibreOJ2241
    LibreOJ2044
    LibreOJ2043
    LibreOJ2045
    LibreOJ2042
    LibreOJ2097
    洛谷P4175
    POJ2888
  • 原文地址:https://www.cnblogs.com/sirdong/p/12000817.html
Copyright © 2011-2022 走看看