【问题标题】:Why is $.getJSON returning ParseError with valid JSON file?为什么 $.getJSON 返回带有有效 JSON 文件的 ParseError?
【发布时间】:2021-03-12 19:24:41
【问题描述】:

我正在尝试从本地文件中获取 JSON 数据:

$.getJSON(file, function(json_data) {
   console.log(json_data);
}).fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); });

但是尽管我的 file 根据https://jsonlint.com/ 是一个有效的 JSON 文件,但我总是得到 ParseError。

我尝试通过 $.get(...) 请求获取内容,但如果我这样做了,我会得到 <empty string> 内容。

谁能帮帮我?

【问题讨论】:

  • 你能发布你的json文件吗?或者至少使用另一个 json 验证器来查看您的文件是否“真的”有效?
  • 我的文件是一个有效的 JSON 文件:- 共享文件 json
  • 那么错误信息是什么?
  • 我宁愿不共享它,但这样一个简单的文件也会出现同样的错误:{"a":"b"}
  • @epascarello 警报是:“getJSON 请求失败!解析器错误”

标签: javascript jquery json ajax


【解决方案1】:
var getProductDataFromJson = new Promise(
  function (resolve) {
     $.getJSON("https://raw.githubusercontent.com/bmehler/product/main/product.json", function(data) { 
         resolve(data);
     });     
  }
);

 getProductDataFromJson
    .then(function (data) {
         console.log('data', data);
    })
    .catch(function (error) {
         console.log(error.message);
    });

这段代码应该可以工作。只需复制我的 json 文件并输入您的数据即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2016-11-11
    • 2013-01-18
    相关资源
    最近更新 更多