2017-03-08 66 views
1

我试图在JSON-LD中完成某些产品架构,但需要动态输出一些字符串。我举出以下一些样本标记: -使用if语句动态构建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

完全构建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); 
}); 
+0

正是我在寻找并帮助我动态构建JSON!谢谢 :) – zigojacko