【问题标题】:Troubles with reading JSON file读取 JSON 文件的问题
【发布时间】:2020-02-25 14:31:13
【问题描述】:

我无法在 js 中读取 json 文件。我尝试了下面的代码,但出现错误:Uncaught SyntaxError: Unexpected token ':'

    <script>
    function loadJSON(callback) {   
      var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
      xobj.open('GET', 'weather.json', true);
      xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(JSON.parse(xobj.responseText));
        }
      };
    }

    //usage:
    loadJSON(function(json) {
      console.log(json); 
    });
    </script>

我的 json 文件包含这样的数据:

{
   "RegionPK{region='kirovohrad', observation=6, forecast=12, level=100000.0}":{
      "temperatureStatistics":{
         "count":26,
         "sum":123.400146484375,
         "min":3.850006103515625,
         "max":6.75,
         "average":4.746159480168269
      },
      "humidityStatistics":{
         "count":26,
         "sum":1797.7999954223633,
         "min":56.599998474121094,
         "max":79.4000015258789,
         "average":69.1461536700909
      },
      "cloudnessStatistics":{
         "count":17,
         "sum":0.0,
         "min":0.0,
         "max":0.0,
         "average":0.0
      }
   },
   "RegionPK{region='dnipropetrovsk', observation=0, forecast=3, level=100000.0}":{
      "temperatureStatistics":{
         "count":46,
         "sum":90.8670654296875,
         "min":1.181884765625,
         "max":2.481903076171875,
         "average":1.975370987601902
      },
      "humidityStatistics":{
         "count":46,
         "sum":3598.199996948242,
         "min":72.0,
         "max":83.30000305175781,
         "average":78.22173906409222
      },
      "cloudnessStatistics":{
         "count":32,
         "sum":0.0,
         "min":0.0,
         "max":0.0,
         "average":0.0
      }
   }
}

此处出现错误:RegionPK{region='kirovohrad',observation=6,forecast=12,level=100000.0}":{ 但同时我的文件已通过 json 验证。那么,我可以以任何方式或我的方式阅读此文件吗? json 文件无效?

【问题讨论】:

  • 解析前的摘录是xobj.responseText的准确内容吗?

标签: javascript json file


【解决方案1】:

您提供的数据是一个 JSON 对象,您不能将它与 JSON.parse 一起使用 - 应该传递一个 JSON 字符串,然后返回一个 JSON 对象。

对于您提供的数据,如果我调用JSON.parse(JSON.stringify(jsonFile))(其中 jsonFile 是您在上面给出的数据)它会返回一个正确的 JSON 对象,所以我认为数据没有任何问题(因为您已提供)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多