检查特定的JSON结果,如果不存在则停止



首先,我是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]中的"country"标记是否匹配的方法;英国";在我对脚本执行任何操作之前,如果数据匹配,则继续执行脚本的其余部分,如果"country"标记与"United Kingdom"以外的任何内容匹配,则停止脚本。

有人有什么想法愿意分享吗。

提前感谢:

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

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。

相关内容

最新更新