如何通过类似道具的API过滤JSON返回?

时间:2018-03-30 19:47:15

标签: javascript arrays json

我正在使用thecocktaildb API,并试图拉出成分并将其输出到页面。

他们提供的JSON列出了

的成分
strIngredient1:"Lager"
strIngredient2:"Tequila"
strIngredient3:""
...
strIngredient15:""

我一直试图弄清楚我是如何做到这一点所以它会循环或将strIngredient1-15分组到strIngredients所以我可以有一个只有成分的数组,并过滤​​掉strIngredient是否为空。 我也希望将它们按顺序排列,所以当我将它与测量结果相匹配时,它会有意义。

strMeasure1:"16 oz "
strMeasure2:"1.5 oz"
strMeasure3:""
...
strMeasure4:""

1 个答案:

答案 0 :(得分:1)

让我说我喜欢你对API的喜好!

为玛格丽塔测试一下:

https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita

调用它将给出一个JSON数组(结果),我们可以这样解析:

    if (!result || !result.drinks || result.drinks.length <= 0) {
        console.log('No drinks found!!');
        return;
    }

    // Get the first drink.
    var drink = result.drinks[0];

    let index = 1;
    let ingredientArray = [];
    while (drink['strIngredient' + index]) {
        ingredientArray.push({name: drink['strIngredient' + index], amount: drink['strMeasure' + index] ? drink['strMeasure' + index]: "A dash "});
        index++;
    }

    console.log('Drink: ', drink.strDrink);
    console.log('Ingredients: ');
    ingredientArray.forEach((ingredient) => {
        console.log(`${ingredient.amount} of ${ingredient.name}`)
    });

我得到了结果:

Drink:  Margarita
Ingredients:
1 1/2 oz  of Tequila
1/2 oz  of Triple sec
1 oz  of Lime juice
A dash  of Salt

要在HTML页面中显示,我们可以使用类似的代码(两个文件:test.html和app.js):

<强>的test.html

<html>
<head>
      <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
      <script src="app.js"></script>
</head>
<body topmargin="40" leftmargin="40" onLoad="downloadCocktail()">
 <div id="result">Loading..</div>
 </br>
 <button onClick="downloadCocktail()">Download cocktail</button> : <input type="text" id="cocktail" value="Margarita"><br>
 </body>
</html>

在同一目录中:

<强> app.js

function outputDrink(drink)
{    
    console.log(drink);
    let index = 1;
    let ingredientArray = [];
    while (drink['strIngredient' + index]) {
        ingredientArray.push({name: drink['strIngredient' + index], amount: (drink['strMeasure' + index]||'').trim() ? drink['strMeasure' + index]: "A dash "});
        index++;
    }

    var text = '';

    text += `<b>Drink: </b><br/>${drink.strDrink}<br/><br/>`;
    text += `<b>Glass: </b><br/>${drink.strGlass}<br/><br/>`;
    text += '<b>Ingredients:</b></br>';
    ingredientArray.forEach((ingredient) => {
        text += `<li>${ingredient.amount} of ${ingredient.name}</li>`;
    });

    text += `</br><b>Instructions: </b></br>${drink.strInstructions}<br/>`;

    $( "#result" ).html(text);     
}

function downloadCocktail(){
    let cocktailName = $('#cocktail').val();
    console.log('Downloading details for: ', cocktailName);
    var cocktail = encodeURIComponent(cocktailName);
    $.ajax({
        type: 'GET',
        url:  'https://www.thecocktaildb.com/api/json/v1/1/search.php?s=' + cocktail,
        timeout:5000,
        crossDomain: true,
        dataType:'json',
        success: function(result, status){
            if (!result.drinks || result.drinks.length <= 0) {
                $( "#result" ).html('No drinks found!!');
                return;
            }

            // Get the first drink.
            var drink = result.drinks[0];
            outputDrink(drink);  
        },
        error: function (errorMessage) {
            console.error(errorMessage);
        }
    });
}

您的网页看起来像这样:

饮料:玛格丽塔 玻璃:鸡尾酒杯
成分:

  • 1 1/2盎司龙舌兰酒
  • 1/2盎司的三秒
  • 1盎司的青柠汁
  • 一点盐

项目目录:

\
  - test.html
  - app.js

此外,您可以输入所需的鸡尾酒,然后单击下载以获取成分。

干杯!!