來源格式與預期記錄
這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。
本例 payload 為無循環的 JSON 形資料,逐層訪問物件欄位,以路徑陣列列葉值。純量陣列整組當一個答案,含物件的陣列拒絕。空物件也明列 {},不省略。路徑每段分開保存,不拼成文字。
| 個案 | 輸入記錄(JSON) | 預期輸出(JSON) |
|---|---|---|
| 整理巢狀答案值 | {"payload":{"profile":{"name":"Ada","tags":["new","trial"]},"optIn":false}} | {"ok":true,"value":{"answers":[{"path":["profile","name"],"value":"Ada"},{"path":["profile","tags"],"value":["new","trial"]},{"path":["optIn"],"value":false}]}} |
| 拒絕陣列內物件 | {"payload":{"tags":[{"code":"new"}]}} | {"ok":false,"error":"LEAF_ARRAY"} |
| 保留空物件 | {"payload":{"profile":{}}} | {"ok":true,"value":{"answers":[{"path":["profile"],"value":{}}]}} |
在本機執行轉換
把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。
import assert from 'node:assert/strict';
function leafAnswers(i){
const fail=error=>({ok:false,error});if(!i||!Object.hasOwn(i,'payload'))return fail('LEAF_PAYLOAD');
const scalar=v=>v===null||typeof v==='string'||typeof v==='boolean'||(typeof v==='number'&&Number.isFinite(v));
const answers=[];let error;
const visit=(value,path)=>{
if(scalar(value)){answers.push({path,value});return;}
if(Array.isArray(value)){if(!value.every(scalar)){error='LEAF_ARRAY';return;}answers.push({path,value:[...value]});return;}
if(value&&typeof value==='object'){
const entries=Object.entries(value);if(!entries.length){answers.push({path,value:{}});return;}
for(const [key,v]of entries)visit(v,[...path,key]);return;
}
error='LEAF_VALUE';
};
visit(i.payload,[]);return error?fail(error):{ok:true,value:{answers}};
}
// Original synthetic cases; expected outputs are literal records.
const cases = [
{
"label": "Capture nested answer leaves",
"input": {
"payload": {
"profile": {
"name": "Ada",
"tags": [
"new",
"trial"
]
},
"optIn": false
}
},
"expected": {
"ok": true,
"value": {
"answers": [
{
"path": [
"profile",
"name"
],
"value": "Ada"
},
{
"path": [
"profile",
"tags"
],
"value": [
"new",
"trial"
]
},
{
"path": [
"optIn"
],
"value": false
}
]
}
}
},
{
"label": "Reject object-valued array",
"input": {
"payload": {
"tags": [
{
"code": "new"
}
]
}
},
"expected": {
"ok": false,
"error": "LEAF_ARRAY"
}
},
{
"label": "Preserve empty object",
"input": {
"payload": {
"profile": {}
}
},
"expected": {
"ok": true,
"value": {
"answers": [
{
"path": [
"profile"
],
"value": {}
}
]
}
}
}
];
for (const sample of cases) {
const actual = leafAnswers(sample.input);
assert.deepEqual(actual, sample.expected);
console.log(sample.label, JSON.stringify(actual));
}
判清邊界個案
tags=["new","trial"] 是否拆成兩個索引答案?
查看參考答案
不拆,整組放在 ["profile","tags"] 的一個答案。optIn=false 是另一個明確答案;空 profile 則產生值為 {} 的答案。