訂明本例驗收任務
假設本機串流有按次序文字段及明示 ended 布林。先按次序接文字,但 ended 為真才解析 JSON。前段即使可解析也仍未完;已結束而格式不符便列解析錯誤,不造部分物件。
- 按序接提供的文字段
- 等明示結束狀態
- 解析完整文字或保留錯誤
未結束便待完成;結束後解析失敗須覆核原文。
使用已填個案
| 個案 | 已提供輸入 | 預期結構化結果 | 判斷及原因 |
|---|---|---|---|
| 可解析前段但尚未結束 | {"chunks":["{\"x\":","1}"],"ended":false} | {"status":"incomplete"} | 明示完成欄仍為假。 |
| 已結束的完整物件 | {"chunks":["{\"x\":","1}"],"ended":true} | {"status":"parsed","value":{"x":1}} | 結束狀態及完整解析結構都具備。 |
| 串流段是數值 | {"chunks":[1],"ended":true} | {"status":"invalid-text-chunks"} | 文字欄不可把數值1轉成可解析 JSON 字串。 |
| 已結束但資料格式錯 | {"chunks":["{\"x\":"],"ended":true} | {"status":"parse-error"} | 結束標記不能修好無效 JSON。 |
逐步處理 ended-broken-json 個案,須得到甚麼結果?原因是甚麼?
查看參考答案
{"status":"parse-error"}。結束標記不能修好無效 JSON。
執行完整本機驗算
import assert from 'node:assert/strict';
function evaluate(x){
if(!Array.isArray(x.chunks)||x.chunks.some(chunk=>typeof chunk!=='string'))return {status:'invalid-text-chunks'};
if(typeof x.ended!=='boolean')return {status:'invalid-end-state'};if(!x.ended)return {status:'incomplete'};
try{return {status:'parsed',value:JSON.parse(x.chunks.join(''))};}catch{return {status:'parse-error'};}
}
const cases = [
{
"id": "valid-prefix-not-ended",
"input": {
"chunks": [
"{\"x\":",
"1}"
],
"ended": false
},
"expected": {
"status": "incomplete"
}
},
{
"id": "ended-valid-object",
"input": {
"chunks": [
"{\"x\":",
"1}"
],
"ended": true
},
"expected": {
"status": "parsed",
"value": {
"x": 1
}
}
},
{
"id": "nontext-stream-chunk",
"input": {
"chunks": [
1
],
"ended": true
},
"expected": {
"status": "invalid-text-chunks"
}
},
{
"id": "ended-broken-json",
"input": {
"chunks": [
"{\"x\":"
],
"ended": true
},
"expected": {
"status": "parse-error"
}
}
];
for (const c of cases) assert.deepEqual(evaluate(c.input), c.expected, c.id);
console.log(JSON.stringify({checked:cases.length,caseIds:cases.map(c=>c.id)}));
保留原文字段及完成狀態。本例沒有接即時串流或外部操作;解析成物件仍須另核驗收要求。