使用if语句动态构建JSON-LD产品模式

时间:2017-03-08 16:15:28

标签: json

我正在尝试在JSON-LD中完成一些产品架构,但是一些字符串需要动态输出。我在下面添加了一些示例标记: -

$(document).ready(function() {
  var el = document.createElement('script');
  el.type = 'application/ld+json';
  el.text = JSON.stringify( {
    "@context": "http://schema.org/",
    "@type": "Product",
    "name": "ProductName",
    "aggregateRating": {
      "@type": "AggregateRating",
      "worstRating": "1",
      "bestRating": "5",
      "ratingValue": "ProductRatingValue",
      "reviewCount": "ProductReviewCount"
    },
  });
  document.querySelector('head').appendChild(el);
});

如果某个产品不包含任何评论,则ratingValuereviewCount输出0会导致验证者错误地评估评分'

是否有基于JSON的方法仅根据if语句输出ratingValuereviewCount?我已经查看过相当多的文档并且没有找到如何在语法上实现这一点,尽管我怀疑它肯定有可能......?

1 个答案:

答案 0 :(得分:2)

完全构建JSON 之前将其字符串化。

$(document).ready(function() {
  var el = document.createElement('script');
  el.type = 'application/ld+json';
  var jsonLd = {
    "@context": "http://schema.org/",
    "@type": "Product",
    "name": "ProductName",
    "aggregateRating": {
      "@type": "AggregateRating",
      "ratingValue": "ProductRatingValue",
      "reviewCount": "ProductReviewCount"
    }
  };
  if (yourRatingValue > 0) { jsonLd.ratingValue = yourRatingValue; }
  if (yourReviewCount > 0) { jsonLd.reviewCount = yourReviewCount; }
  el.text = JSON.stringify(jsonLd);

  document.querySelector('head').appendChild(el);
});
相关问题