测试名称是否在JSON中可用,如果没有做其他JSON请求

Test if name is available in JSON and if not do other JSON request

本文关键字:JSON 如果没有 请求 其他 是否 测试      更新时间:2023-09-26

我想知道测试JSON文件中是否存在名称的最佳方法是什么。如果该名称不存在,则加载另一个JSON文件。我可以测试这个名字是否存在。我有麻烦加载新的JSON文件时,名称不存在。

在人们开始投票之前。我知道简单的if else行不通,但这是我的问题。那么你如何设置一些'if' 'else'函数来测试一个名字是否存在?

假设我想测试JSON文件中是否存在'url1'中的"name"

 $.getJSON(url1, function (json){ 
    var names = []; 
   if(json.hasOwnProperty('name')){
      // name is present in here so build some HTML
    } else {
      // name is not present in here so get a different JSON file and build other html
      $.getJSON(url2, function (json){
      }); 
    }
  });

这样做的问题是,当'name'在来自url1的JSON中不存在时,其他JSON(来自url2)不会被调用。

为了澄清一些事情,我做了一个小提琴

你可以使用并发。

function JsonGetter(listOfJsonUrls, name, i) {
    $.getJSON(listOfJsonUrls[i], function (json) {
            if (json.hasOwnProperty(name)) {
                // name is present in here so build some HTML
            } else {
                JsonGetter(listOfJsonUrls, name, i + 1)
            });
    }
}

这样写:

JsonGetter(['url1','url2'], 'name', 0);