zoukankan      html  css  js  c++  java
  • angularjs SyntaxError: Unexpected token  in JSON at position 0

    使用NodeJs读取json格式的文件,转换成对象时报错 :SyntaxError: Unexpected token in JSON at position 0,这个问题查了两三个小时,记录一下解决方法。

    JSON格式的文件:

    {
        "token": "zeroes", 
        "appid": "wxce06f44f4233cfe954"
    }

    正确的读写方式:

        //读取配置文件
            function readConfig() {
                var configStr = $scope.fs.readFileSync(config.weixin.path, 'utf8');
                console.log(configStr);
                //没有下面这行就抛异常
                configStr = JSON.stringify(configStr);
                return JSON.parse(configStr);        
            }

    上面的方式只是不报错了,但JSON.parse 之后是string类型不是对象。

    最后还是用到了 eval:

      $scope.readConfig = function () {
                try {
                    var configStr = $scope.fs.readFileSync(config.weixin.path, 'utf8');
                    console.log(configStr);
                    var obj = eval('(' + configStr + ')');
                    $scope.weixin.appid = obj.appid;
                    $scope.weixin.appsecret = obj.appsecret;
                    $scope.weixin.qrcodeurl = obj.qrcodeurl;
                }
                catch (e) {
                    console.log(e);
                    alert("读取微信配置文件失败");
                }
            }
  • 相关阅读:
    beanutils中WrapDynaBean
    beanutils中Lazy
    beanutils中jdbc
    beanutils设置参数和获取参数
    beanutils获取带参数get方法
    beanutils通过SimpleProperty使用get或set方法赋值
    C3P0配置
    Codeforces Round #587 (Div. 3)
    Codeforces Round #589 (Div. 2)
    Codeforces Round #588 (Div. 2)
  • 原文地址:https://www.cnblogs.com/zeroes/p/angularjs-json-parse-exception.html
Copyright © 2011-2022 走看看