構造化データ(JSON-LD形式)をJavaScriptで動的に描写する方法
2024/05/22
あるサイトに構造化データをJSON-LD形式で出力させたかった。ただ、当該環境ではPHP等サーバサイドのプログラム言語は使えないといった制約があった。どうしたものか調べたところJavaScriptで出力できるようなので対応方法をメモ。
構造化データ例
Googleによるとブログ等の記事ページの場合は以下のような構造化データが必要とのことなので、本記事ではこちらを出力させたい。
{
"@context": "https://schema.org",
"@type": "NewsArticle",
"headline": "Title of a News Article",
"image": [
"https://example.com/photos/1x1/photo.jpg",
"https://example.com/photos/4x3/photo.jpg",
"https://example.com/photos/16x9/photo.jpg"
],
"datePublished": "2015-02-05T08:00:00+08:00",
"dateModified": "2015-02-05T09:20:00+08:00",
"author": [
{
"@type": "Person",
"name": "Jane Doe",
"url": "https://example.com/profile/janedoe123"
},
{
"@type": "Person",
"name": "John Doe",
"url": "https://example.com/profile/johndoe123"
}
]
}
ソースコード
<script>
let structured_data = {};
//構造化データ作成
structured_data["@context"] = "https://schema.org";
structured_data["@type"] = "NewsArticle";
structured_data["headline"] = "Title of a News Article";
structured_data["image"] = ["https://example.com/photos/1x1/photo.jpg","https://example.com/photos/4x3/photo.jpg","https://example.com/photos/16x9/photo.jpg"];
structured_data["datePublished"] = "2015-02-05T08:00:00+08:00";
structured_data["dateModified"] = "2015-02-05T09:20:00+08:00";
structured_data["author"] = [];
var author_data = {};
author_data["@type"] = "Person";
author_data["name"] = "Jane Doe";
author_data["url"] = "https://example.com/profile/janedoe123";
structured_data["author"].push(author_data);
var author_data = {};
author_data["@type"] = "Person";
author_data["name"] = "John Doe";
author_data["url"] = "https://example.com/profile/johndoe123";
structured_data["author"].push(author_data);
//Json形式に変換
structured_data = JSON.stringify(structured_data);
//出力
let structured_element = document.createElement("script");
structured_element.type = "application\/ld+json";
structured_element.innerText = structured_data;
document.body.appendChild(structured_element);
</script>
実際の運用としては外部サーバーからAjax等でデータを引っ張ってきたり、APIと連携させたりといった使い方も可能。
サンプル
https://taitan916.info/sample/structured_data/
JavaScriptで出力させているためデベロッパーツール等で確認する必要あり。尚、このような出力方法でもGoogleのテストツールでは正常に読み込めたので問題は無さそう。
関連便利サイト
Googleの構造化データテストサイト
https://developers.google.com/search/docs/appearance/structured-data?hl=ja
Json整形サイト
関連記事
-
-
jQueryで要素を移動する方法のまとめ
jQueryで要素を移動する際、insertBefore / insertAft ...
-
-
Leafletで「leaflet-control-geocoder」プラグインを導入して住所検索機能を追加する方法
LeafletとOpenStreetMapでマップを表示させ、テキストボックスに ...
-
-
Leafletにて操作内容を履歴に残し「進む」「戻る」ボタンで履歴を実行できる「Leaflet.NavBar」の利用方法
Leafletにてマップ移動やズーム等、ユーザーの操作内容を履歴に残して、「進む ...
-
-
JavaScript / jQueryで〇番目、最初、最後の要素を指定する方法
jQueryでリストタグ(<li>)の〇番目、最初、最後の要素を指定 ...
-
-
AjaxのJSONP使用でPHPで作った配列をJSに返す方法
AというサイトからBというサイトにAjax通信し、Bの方ではMySQLに接続して ...