javascript - jQuery - 检查 .json 文件是否有效

标签 javascript jquery json

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

代码:

  $.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 中显示错误消息,以便用户知道为什么 div 中没有文本。

我已经尝试过这个,但它不起作用:

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.");
}

这是否可以做到,或者您只能检查一个字符串是否有效?

最佳答案

你可能想要这样的东西:

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

在浏览器中运行此命令的输出是“json 无效”

关于javascript - jQuery - 检查 .json 文件是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31326810/

相关文章:

javascript - 一页中的多个窗口 onclick 事件

javascript - 使用javascript检测上下滚动

php - 使用 AJAX 和 JSON 显示来自 PHP 的 HTML 内容

javascript - 遍历数组和子数组

javascript - http 模块(带有 browserify 的 node.js)不使用 PATCH 方法编写请求正文

Javascript对象删除特定键

javascript - Jquery .load 触发两次,但被调用一次

javascript 函数 .change() 不在克隆元素上运行

json - json 数据源可以保存/包含图像吗?

json - 基于命名空间嵌套和合并 JSON