WordPress上JSON Content Importer的使用
JSON Content Importer
主要拆解概念
JSON Content Importer主要的拆解概念有兩個:
- 就是透過 subloop-array (拆解[]中的資料)與 subloop(拆解{}中的資料) 來解析JSON字串中的各個元件。
- 當多層拆解時,內層的節點存取方式要包含上層的節點名稱。
例如以下的範例,我們透過subloop-array來拆解data時,如果到了拆解attributes時,使用的標籤方式應該會是{data.attributes.title},而不是{attributes.title}。(這可能需要大家實際實驗體會一下)
{
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API paints my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
},
"relationships": {
"author": {
"data": {"id": "42", "type": "people"}
}
}
}],
"included": [
{
"type": "people",
"id": "42",
"attributes": {
"name": "John",
"age": 80,
"gender": "male"
}
}
]
}
範例一
範例網址|https://tourevent.tw/wp-content/plugins/json-content-importer/json/gutenbergblockexample1.json
資料格式
{
"level1": {
"start": "Very good, this is the value of 'start', right out of the JSON-data",
"level2": [{ "key" : "This is the first value of key in the 'level1'-array",
"data": {
"id": 11111,
"type": "aaaa"
}
},
{ "key" : "This is the second value of key in the 'level1'-array",
"data": {
"id": 222,
"type": "bbbb"
}
},
{ "key" : "This is the third value of key in the 'level1'-array",
"data": {
"id": 33333333,
"type": "aaaa"
}
},
{ "key" : "This is the fourth value of key in the 'level1'-array",
"data": {
"id": 4444,
"type": "aaaa"
}
}]
}
}
拆解方式
[jsoncontentimporter url="https://tourevent.tw/wp-content/plugins/json-content-importer/json/gutenbergblockexample1.json" debugmode="0" urlgettimeout="10" basenode="level1"]
{start}<br>{subloop-array:level2:-1}{level2.key} <br> {subloop:level2.data:-1}id: {level2.data.id} <br> {/subloop:level2.data}{/subloop-array:level2}
[/jsoncontentimporter]
- debugmode:2, shows some debug infos;10, all available debug infos.
- basenode:starting point of datasets, the base-node in the JSON-Feed where the data is
Template(以上面的範例來解說)
- {start}:提取basenode下的start標籤內容
- 透過{subloop-array}與{subloop}來迴圈取得資料數值
- {subloop-array:標籤名稱:數量}:在「[ ]」中,迴圈取值的標籤名稱以及要提取的數值個數,如果數量為「-1」,代表提取全部數值
- {subloop:標籤名稱:數量}:在「{ }」中,迴圈取值的標籤名稱以及要提取的數值個數,如果數量為「-1」,代表提取全部數值
範例二
範例網址|https://api.exchangerate-api.com/v4/latest/JPY
資料格式
{"provider":"https://www.exchangerate-api.com","WARNING_UPGRADE_TO_V6":"https://www.exchangerate-api.com/docs/free",
"terms":"https://www.exchangerate-api.com/terms",
"base":"JPY",
"date":"2023-05-22",
"time_last_updated":1684713601,
"rates":{"JPY":1,
"AED":0.0266,
"AFN":0.635,
"ALL":0.747,
"AMD":2.8,
"TWD":0.222,
"ZWL":9.65
}
}
拆解方式
如果我們只需要rates下的TWD匯率
[jsoncontentimporter url="https://api.exchangerate-api.com/v4/latest/JPY" debugmode="0" urlgettimeout="10" basenode=""]
{start}{subloop:rates:1}{rates.TWD} {/subloop:rates}
[/jsoncontentimporter]
- {start}:basenode使用空字串
- 透過{subloop}來迴圈取得資料數值
- {subloop:標籤名稱:數量}:在「{ }」中,迴圈取值的標籤名稱以及要提取的數值個數,如果數量為「-1」,代表提取全部數值。在這個範例上只須提提取一個(唯一)
官方文件連結|Documentation of JSON Content Importer Plugin – WordPress-Plugin JSON Content Importer