You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态更新Schema对应的JSON-LD脚本中的ratingValue与ratingCount字段

动态修改JSON-LD字段实现方案

注意:你提供的原JSON-LD存在语法问题,name字段值"Bat,缺少闭合引号与尾部逗号,解析前需要先修正为合法JSON结构,否则会触发解析错误。

实现逻辑

  • 选中页面中type为application/ld+json的对应script标签
  • 将标签内的文本内容解析为JavaScript对象
  • 修改aggregateRating下的ratingValue和ratingCount字段值
  • 将修改后的对象序列化为JSON字符串,重新写入script标签即可生效

完整代码示例

// 选择JSON-LD脚本标签,若存在多个可添加额外筛选条件
const jsonLdScript = document.querySelector('script[type="application/ld+json"]');

try {
  // 解析JSON-LD内容为JS对象
  const productSchema = JSON.parse(jsonLdScript.textContent);

  // 此处可替换为你业务中动态获取的评分数据
  const updatedRatingValue = "4.8";
  const updatedRatingCount = "136";

  // 校验字段存在后更新值
  if (productSchema?.aggregateRating) {
    productSchema.aggregateRating.ratingValue = updatedRatingValue;
    productSchema.aggregateRating.ratingCount = updatedRatingCount;
  }

  // 序列化后写回原script标签,保留缩进方便调试
  jsonLdScript.textContent = JSON.stringify(productSchema, null, 2);
} catch (err) {
  console.error("JSON-LD格式异常,解析失败:", err);
}

内容的提问来源于stack exchange,提问作者Alex Ami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:06:03