Парсинг обзора JSON API Yelp Fusion - PullRequest
0 голосов
/ 23 июня 2019

Я хочу отображать обзоры на веб-странице, но у меня проблемы с анализом и форматированием JSON. Любая помощь очень ценится. Я могу справиться с разметкой HTML и CSS, мне просто нужно пройтись по каждой новой рецензии и получить рецензента, reviewtext, pictureurl и т. Д.

Пока что можно получить только количество отзывов. Я новичок в JSON, и у меня проблемы с анализом обзоров и получением правильного формата.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
      <title>Ilan's Test</title>
   </head>
   <body>

   <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div id="results">

                </div>
            </div>
         </div>
   </div>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
      <script>
         var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";

         $.ajax({
            url: myurl,
            headers: {
             'Authorization':'Bearer API-KEY-GOES-HERE',
         },
            method: 'GET',
            dataType: 'json',
            success: function(data){
                // Grab the results from the API JSON return
                var totalresults = data.total;
                // If our results are greater than 0, continue
                if (totalresults > 0){
                    // Display a header on the page with the number of results
                    $('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
                    // Itirate through the JSON array of 'reviews' which was returned by the API
                    $.each(data.reviews[id], function(id, review) {
                        // Store each review object in a variable
                        var id = review.id;
                        var reviewtext = reviews[id].text;
                        var reviewrating = reviews[id].rating;
                        // Append our result into our page
                        $('$results').append(reviewtext + reviewrating + reviews);
                  });
                } else {
                    // If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
                    $('#results').append('<h5>We discovered no results!</h5>');
                }
            }
         });     

      </script>
   </body>
</html>

1 Ответ

0 голосов
/ 23 июня 2019

Незначительные ошибки с кодом, но это нормально; каждая ваша функция была немного грязной, и вы случайно использовали $ results в качестве ссылки, которая должна была быть #results; но это все хорошо, что ты получаешь это!

Проверьте код ниже (обратите внимание, что Yelp позволяет получить только 3 отзыва; поэтому, когда вы видите всего 8, выборка не превысит 3);

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
      <title>Ilan's Test</title>
   </head>
   <body>

   <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div id="results">

                </div>
            </div>
         </div>
   </div>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
      <script>
         var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";

         $.ajax({
            url: myurl,
            headers: {
             'Authorization':'Bearer API-KEY-GOES-HERE',
         },
            method: 'GET',
            dataType: 'json',
            success: function(data){
                // Grab the results from the API JSON return
                var totalresults = data.total;
                // If our results are greater than 0, continue
                if (totalresults > 0){ console.log(data);
                    // Display a header on the page with the number of results
                    $('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
                    // Itirate through the JSON array of 'reviews' which was returned by the API
                    $.each(data.reviews, function(i, item) {
                        // Store each review object in a variable
                        var author = item.user.name;
                        var reviewtext = item.text;
                        var reviewrating = item.rating;
                        // Append our result into our page
                        $('#results').append('Author: <b>' + author + '</b><br> Review: ' + reviewtext + '<br>Rating: ' + reviewrating + ' <hr>');
                  });
                } else {
                    // If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
                    $('#results').append('<h5>We discovered no results!</h5>');
                }
            }
         });     

      </script>
   </body>
</html>
...