Remove comma after last object in the Schema array with PHP WordPress Loop

  javascript, json, php

I have a "Product" Google Schema Markup with the pasted loop for the "Reviews".
Here’s a part of the Markup’s code:

     "review": [
            <?php
            $args = array(
            'post_type' => 'my_reviews',
            'category_name' => 'my-product', 
            'paged' => $paged);
    
            $loop = new WP_Query($args);
            if ($loop->have_posts()) :
            while ($loop->have_posts()) : $loop->the_post(); ?>
{
            
            "@type": "Review",
            "reviewRating": {
              "@type": "Rating",
              "ratingValue": "5"
            },
            "author": {
              "@type": "Person",
              "name": "<?php the_title(); ?>"
            },
            "reviewBody": "<?php echo get_the_content(); ?>"},
    <?php
    endwhile;
    endif;
    wp_reset_postdata();
    ?>],
    
          "aggregateRating": {
            "@type": "AggregateRating",
            "ratingValue": "5",
            "bestRating": "5",
            "ratingCount": "<?php echo count_cat_post('My Product'); ?>"
},

Everything works as it should, except that after } of the last object, a comma is still trapped.
And it turns out something like the following:

"review": [{
    "@type": "Review",
    "reviewRating": {
      "@type": "Rating",
      "ratingValue": "5"
    },
    "author": {
      "@type": "Person",
      "name": "John Doe"
    },
    "reviewBody": "Review 1 Content"
  },
  {
    "@type": "Review",
    "reviewRating": {
      "@type": "Rating",
      "ratingValue": "1"
    },
    "author": {
      "@type": "Person",
      "name": "Jane Doe"
    },
    "reviewBody": "Review 2 Content."
  }, <-- this is the comma I need to remove],
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "88",
    "bestRating": "100",
    "ratingCount": "2"
  },

How can I remove it?

Source: Ask PHP

LEAVE A COMMENT