【问题标题】:jQuery - Check if a .json file is validjQuery - 检查 .json 文件是否有效
【发布时间】:2015-09-28 09:05:39
【问题描述】:

我正在使用 .json 文件和 jQuery 的 $.getJSON 用文本填充 divs,我的代码如下所示:

代码:

  $.getJSON("/js/content.json", function (data) {
  $(".lander .title").text(data.lTitle);
  $(".lander .subtitle").text(data.lSubtitle);
  $(".lander .text").html(data.lText).split('\n').join('<br/>');
});

JSON 文件:

{
    "comment": "Landing page",
    "lTitle": "Your webpage",
    "lSubtitle": "Your webpage subtitle",
    "lText": "Edit this text under >js/content.json< ",

    "lDetailsTitle": "Here goes the details title under the landing header.",
    "lDetailsText": "Here goes the details text."

}

我要做的是使用$parseJSON 检查整​​个content.json 是否有效(不仅仅是一个字符串)。我想这样做的原因是 jquery 可以在 DOM 中显示错误消息,以便用户知道为什么 divs 中没有文本。

我试过了,但它不起作用:

var isValid = jQuery.parseJSON("/js/content.json");
if (isValid === true) {} else {
    $("#overlayMessage").css("display", "block");
    $("#overlayMessage .title").text("Oh no, we can't display this page!");
    $("#overlayMessage .text").text("An error occured with the file under: 'js/content.json'. Reason: Invalid.");
}

这有可能吗,还是只能检查一个字符串是否有效?

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:

    你可能想要这样的东西:

    try{
        var json = JSON.parse("invalid json");
    }catch(err){
        console.log('json is invalid');
    }
    

    在浏览器中运行的输出是`json is invalid

    【讨论】:

    • 即使 json 文件有效,也会返回无效。 (我检查了。)
    • 您似乎检查了无效的 json。尝试类似'{ "something":"1" }'
    • 塞巴斯蒂安,你在做什么?一定是个错误。例如JSON.parse("{}") 工作。
    • 运行它......什么?
    【解决方案2】:

    提供一个fail() 回调来捕获来自getJSON() 的解析错误

    $.getJSON('/foo/bar.json')
      .done(function(d) {
        alert("success");
      })
      .fail(function(d) {
        alert("error");
      });
    

    相关:Why does $.getJSON silently fail?

    【讨论】:

    • 谢谢!正是我想要的。这很好用。
    【解决方案3】:

    jQuery.parseJSON() 解析 JSON 字符串,但您提供了 URI。您可以使用jQuery.get() 获取JSON 文本,然后使用jQuery.parseJSON() 检查它是否有效。

    $.get( "/js/content.json", function( data ) {
        try  {
            var jsonObj = jQuery.parseJSON( data );
        } catch(err) {
            $("#overlayMessage").css("display", "block");
            $("#overlayMessage .title").text("Oh no, we can't display this page!");
            $("#overlayMessage .text").text("An error occured with the file under: 'js/content.json'. Reason: Invalid.");
        }
    });
    

    【讨论】:

    • 由于某种原因,这总是返回 true,并且我使 json 无效,似乎不起作用。
    猜你喜欢
    • 2015-11-26
    • 2015-11-15
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2020-08-20
    • 2013-12-07
    相关资源
    最近更新 更多