遍历JSON-LD生成用户评论列表在GSDTT报错求助
问题分析与解决方案
核心问题拆解
你遇到的两个问题其实是关联的:
- Google结构化数据测试工具(GSDTT)的JSON-LD语法错误:
application/ld+json类型的script标签要求内容是严格的纯JSON格式,不能包含任何JavaScript语法(比如你写的var jsonld = ...变量声明)。GSDTT会按照JSON规范解析这个脚本,开头的var直接违反了JSON语法规则,导致报错。 - 页面JS代码无法运行:你的JSON-LD脚本里的内容是字符串,不是全局变量
jsonld,所以直接访问jsonld会报「变量未定义」错误;之前尝试的JSON.parse写法可能因为脚本内容包含JS语法(var声明),解析时也会失败。
修复步骤
1. 修正JSON-LD脚本(解决GSDTT报错)
把application/ld+json脚本里的内容改成纯JSON,去掉var jsonld =声明:
<script id="jsonData" type="application/ld+json"> { "@context": "http://schema.org", "@type": "Product", "image": "https://www.myurl.com/media/db3e3b23f81585_M.jpg", "name": "Test name", "description": "Test review desc.", "offers": { "@type": "AggregateOffer", "availability": "http://schema.org/InStock", "highPrice": "5195.00", "lowPrice": "2595.00", "offerCount": "1", "priceCurrency": "ZAR", "priceValidUntil": "2020-09-30", "url": "https://www.myurl.com/" }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5", "bestRating": "5", "reviewCount": "2" }, "review": [ { "@type": "Review", "author": " Meagen", "description": "Test review desc", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "5", "worstRating": "1" } }, { "@type": "Review", "author": " Ericka", "description": "Test review desc", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "5", "worstRating": "1" } } ] } </script>
2. 修正JS代码(解决无法运行问题)
通过DOM获取JSON-LD脚本的内容,再用JSON.parse转换成JavaScript对象,同时优化代码规范:
<script type="text/javascript"> // 正确获取并解析JSON-LD内容 const jsonldScript = document.getElementById('jsonData'); const jsonld = JSON.parse(jsonldScript.innerText); const arrayLength = jsonld.review.length; const outline = document.createElement('div'); outline.className = 'outline'; document.body.appendChild(outline); for (let i = 0; i < arrayLength; i++) { const inside = document.createElement('div'); inside.className = 'inside'; outline.appendChild(inside); // 直接用已获取的outline元素,避免重复DOM查询 // 评论描述(用textContent更安全,不用JSON.stringify) const desc = document.createElement('div'); desc.className = 'desc'; desc.textContent = jsonld.review[i].description; inside.appendChild(desc); // 作者与评分信息 const auth = document.createElement('p'); auth.className = 'author'; auth.textContent = `${jsonld.review[i].author} rated this tour ${jsonld.review[i].reviewRating.ratingValue} out of 5`; inside.appendChild(auth); // 评分显示 const score = document.createElement('p'); score.className = 'score'; score.textContent = `${jsonld.review[i].reviewRating.ratingValue} out of 5`; inside.appendChild(score); } </script>
额外优化说明
- 用
textContent替代innerHTML:避免不必要的HTML解析,更安全且性能更好。 - 使用
const/let声明变量:避免全局变量污染,符合现代JavaScript规范。 - 减少DOM查询:直接复用已获取的DOM元素(比如
outline),提升代码运行效率。
内容的提问来源于stack exchange,提问作者ZADorkMan
相关产品推荐
相关产品推荐

