如何将JavaScript对象格式化为符合Schema规范的JSON适配SEO?
解决面包屑Schema格式无效的问题
嘿,我明白你的困扰了!问题出在你构建itemListElement的方式上——你把本应是数组的列表项,错误地包装成了一个对象再塞进数组里,这就导致Google无法识别正确的结构。
问题根源
看这段多余的代码:
for (var i = 0; i < tempSchemaItems.length; ++i) { finalSchemaObj[i] = tempSchemaItems[i]; }
tempSchemaItems本身已经是一个包含所有ListItem对象的数组了,但你却把它转成了一个带索引键的对象({0: {...}, 1: {...}}),然后又把这个对象放进了itemListElement的数组中,最终结构变成了itemListElement: [ {0: ...} ],这完全不符合Schema.org的规范。
修改后的完整函数
直接去掉那个多余的循环,把tempSchemaItems直接赋值给itemListElement就行:
function populateJsonLDScript(data) { if (typeof (data) != "undefined" && data != null) { var tempSchemaItems = []; for (var i = 0; i < data.length; i++) { var tempSchemaData = {}; tempSchemaData["@type"] = "ListItem"; tempSchemaData["position"] = data[i].DisplayOrder; tempSchemaData["item"] = { "@id": data[i].CanonicalURL, "name": data[i].Name }; tempSchemaItems.push(tempSchemaData); } // 去掉多余的finalSchemaObj转换,直接用现成的数组 var scriptSchema = document.createElement('script'); scriptSchema.type = 'application/ld+json'; scriptSchema.text = JSON.stringify({ "@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": tempSchemaItems // 这里直接传入数组 }); if ($('head script[type="application/ld+json"]').length > 0) { $('head script[type="application/ld+json"]').remove(); $("head").append(scriptSchema); } else { $("head").append(scriptSchema); } } }
修改说明
- 删除了
finalSchemaObj的定义和循环转换步骤——因为tempSchemaItems已经是我们需要的数组结构,完全没必要多此一举。 - 在
JSON.stringify中,把itemListElement: [finalSchemaObj]改成了itemListElement: tempSchemaItems,直接将列表项数组赋值给它。
验证输出
修改后生成的Schema数据会变成你想要的正确格式:
{ "@context":"http://schema.org", "@type":"BreadcrumbList", "itemListElement":[ { "@type":"ListItem", "position":0, "item": { "@id":"http://example.com", "name":"Home" } }, { "@type":"ListItem", "position":1, "item":{ "@id":"http://example.com/jewelry", "name":"Jewelry" } }, { "@type":"ListItem", "position":2, "item":{ "@id":"http://example.com/jewelry/necklaces-pendants", "name":"Necklaces & Pendants" } } ] }
这样Google就能正确识别你的面包屑Schema了!
内容的提问来源于stack exchange,提问作者Daniel Smith
相关产品推荐
相关产品推荐

