如何在生成的JSON-LD中隐藏数字数组键?
解决JSON-LD生成时出现数组键的问题
我正尝试为网站添加JSON-LD,现有一个JSON数组,但因数组键的存在导致其无效。我通过以下方式追加数组数据:
$data[] = $extra_array_data;
我原本以为这样不会生成0、1、2这类数组键,但转换为JSON时却出现了。生成的JSON如下:
{ "@context": "https://schema.org", "@graph": { "0": { "@type": [ "WebPage" ], "@id": "https://example.com/#website", "url": "https://example.com/", "name": "example.com", "description": null, "inLanguage": "nl" }, "@type": [ "WebPage" ], "@id": "https://example.com/#webpage", "url": "https://example.com/contact", "name": null, "isPartOf": { "@id": "https://example.com#website" }, "datePublished": "2023-03-13T21:29:43.3600Z", "dateModified": "2023-03-13T21:29:43.3600Z", "description": "", "inLanguage": "nl-NL", "potentialAction": { "@type": "ReadAction", "target": [ "https://example.com/contact" ] } } }
JSON编码代码如下:
$json_data = json_encode($return_data, JSON_UNESCAPED_UNICODE);
问题原因
核心问题在于@graph对应的PHP结构被搞成了关联数组,而不是JSON-LD要求的索引数组。你用$data[] = $extra_array_data追加数据时,如果$data原本已经是带@type、@id这类键的关联数组,再用[]追加就会自动给新元素加上数字索引(0、1...),转成JSON后就出现了"0": {...}这种不符合规范的结构。
JSON-LD的@graph必须是方括号包裹的JSON数组,而不是花括号包裹的键值对对象。
修复方法
- 先把
@graph初始化为空索引数组:$return_data['@graph'] = []; - 往
@graph里加内容时,直接用索引数组的追加方式:// 加入第一个网页数据 $return_data['@graph'][] = [ "@type" => ["WebPage"], "@id" => "https://example.com/#website", "url" => "https://example.com/", "name" => "example.com", "description" => null, "inLanguage" => "nl" ]; // 加入第二个网页数据 $return_data['@graph'][] = [ "@type" => ["WebPage"], "@id" => "https://example.com/#webpage", "url" => "https://example.com/contact", "name" => null, "isPartOf" => ["@id" => "https://example.com#website"], "datePublished" => "2023-03-13T21:29:43.3600Z", "dateModified" => "2023-03-13T21:29:43.3600Z", "description" => "", "inLanguage" => "nl-NL", "potentialAction" => [ "@type" => "ReadAction", "target" => ["https://example.com/contact"] ] ]; - 这样编码后的JSON就会是符合要求的结构:
{ "@context": "https://schema.org", "@graph": [ { "@type": ["WebPage"], "@id": "https://example.com/#website", "url": "https://example.com/", "name": "example.com", "description": null, "inLanguage": "nl" }, { "@type": ["WebPage"], "@id": "https://example.com/#webpage", "url": "https://example.com/contact", "name": null, "isPartOf": { "@id": "https://example.com#website" }, "datePublished": "2023-03-13T21:29:43.3600Z", "dateModified": "2023-03-13T21:29:43.3600Z", "description": "", "inLanguage": "nl-NL", "potentialAction": { "@type": "ReadAction", "target": ["https://example.com/contact"] } } ] }
注意事项
- 检查初始化逻辑,别一开始就把
@graph设为关联数组。 - 合并数据时优先用索引数组的追加方式,别混合关联数组操作。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

