【问题标题】:Check for a specific JSON result and stop if not present检查特定的 JSON 结果,如果不存在则停止
【发布时间】:2022-01-26 10:58:10
【问题描述】:

首先,我是 Javascript 和编码的新手,所以如果我的代码不够整洁或简洁,请随时提出整理方法。

我看到了一些与此主题类似的问题,但没有什么能满足我的特别需要。

我有一个运行良好的 JS 代码,它接受 JSON 输入并返回特定值:

var subtitle = document.getElementById("demo");
var title = document.getElementById("title_location");
var para1 = document.getElementById("para1");

navigator.geolocation.getCurrentPosition(showPosition);

function showPosition(position) {

  var url = "https://api.opencagedata.com/geocode/v1/json?q=52.773322+-1.552661&key=592431a9da4a45b686bc75eafb005cc1" //Swadlincote (already a city so doesnt need replacing)


  fetch(url)
    .then(response => response.json())
    .then(data => {
      console.log(data)
      console.log(data.results[0].components)


      var stringified = JSON.stringify(data);
      console.log("this is the stringified json before replacement: " + stringified)
      stringifiedR = stringified.replace('"town"', '"city"');
      console.log("this is the stringified json after replacement: " + stringifiedR)
      var jsonObject = JSON.parse(stringifiedR);
      console.log(jsonObject)
      console.log("stringified city: : " + jsonObject.results[0].components.city)

      subtitle.innerHTML = "Subtitle goes here: " + jsonObject.results[0].components.city
      title.innerHTML = "Page Title Goes Here: " + jsonObject.results[0].components.city
      para1.innerHTML = "1st paragraph of text goes here: " + jsonObject.results[0].components.city
    })

}

这很好用,并从 data.results[0].components.city 返回值,这是我需要的。

我正在寻找的是一种在我对脚本执行任何操作之前检查 data.results[0].components.country 中的“国家”标签是否与“英国”匹配的方法,如果数据匹配,请继续脚本的其余部分,如果“国家”标签匹配“英国”以外的任何内容,则停止脚本。

是否有人愿意分享任何想法。

提前致谢:

【问题讨论】:

  • 为什么不使用简单的ifif(data.results[0].components.country === 'United Kingdom'){//run}

标签: javascript html parsing


【解决方案1】:

看起来你只需要做一个比较:

if (jsonObject.results[0].components.country === 'United Kingdom') { 
    console.log('is United Kingdom')
    // rest of what you want to do
} else {
    console.log('is not United Kingdom')
}

您可能还希望构建一些灵活性(例如,如果返回的数据可能没有被清除输入,则比较不区分大小写)。

更多对比信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

我还建议不要公开发布您的 api 密钥(特别是如果您必须付费使用 api 或因过度使用而受到限制)。在这种情况下,最好发布一些示例 JSON。

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 2019-02-15
    • 2016-08-25
    • 2019-05-23
    • 2017-04-24
    • 2015-01-08
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多