Safari解析JSON-LD抛出TypeError错误的解决方法求助
Safari下JSON-LD脚本报错的合规修复方案
问题重现
我们的HTML页面包含一段Schema.org的JSON-LD脚本,在Safari浏览器打开时触发错误:
TypeError: undefined is not an object (evaluating 'r["@context"].toLowerCase')
尝试给最后一个属性/对象加尾随逗号能临时解决,但这违反了JSON规范,需要合规的修复方式。
原因分析
这是Safari旧版本对单元素数组包裹的JSON-LD解析存在兼容性bug——当数组仅包含单个对象时,解析器可能出现异常,导致无法正确识别@context字段。
合规修复方案
方案1:移除外层数组,直接输出单个JSON对象(推荐)
JSON-LD规范本身支持单个顶级对象,不需要强制用数组包裹。修改后的脚本如下:
<script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Organization", "name": "Parqet", "url": "https://www.parqet.com/", "logo": "https://www.parqet.com/logos/parqet_logo_pos.svg", "sameAs": [ "https://www.facebook.com/parqetcom", "https://twitter.com/ParqetApp", "https://www.instagram.com/ParqetApp/", "https://www.youtube.com/channel/UC4LOcElG8Z73Hvgbbp3m1KQ", "https://www.linkedin.com/company/parqet/", "https://github.com/tresorone" ] } </script>
这个改动既完全符合JSON和JSON-LD规范,又能彻底规避Safari的解析bug。
方案2:保留数组结构但添加冗余占位(不推荐)
如果业务上必须保留数组格式,可以在数组中添加一个空的占位对象(但会引入无效数据,仅作应急备选):
<script type="application/ld+json"> [ { "@context": "http://schema.org", "@type": "Organization", "name": "Parqet", "url": "https://www.parqet.com/", "logo": "https://www.parqet.com/logos/parqet_logo_pos.svg", "sameAs": [ "https://www.facebook.com/parqetcom", "https://twitter.com/ParqetApp", "https://www.instagram.com/ParqetApp/", "https://www.youtube.com/channel/UC4LOcElG8Z73Hvgbbp3m1KQ", "https://www.linkedin.com/company/parqet/", "https://github.com/tresorone" ] }, {} ] </script>
验证结果
方案1修改后,在Safari中打开页面不再报错,同时搜索引擎等依赖JSON-LD的服务也能正常解析内容。
内容的提问来源于stack exchange,提问作者ProblemsOfSumit
相关产品推荐
相关产品推荐

