# JSON 陣列後多了引用編號：解析器怎麼擋住壞尾段

- URL: https://justfly.idv.tw/json-array-citation-suffix-validation/
- 日期: 2026-11-30
- 分類: 技術筆記
- 標籤: Gemini, javascript, JSON, n8n

`[{"a":1}] [1.3.3]` 看起來像一份資料加一串編號，整段交給 `JSON.parse` 卻會失敗。把第二組中括號直接丟掉，又可能藏起另一份資料或截斷片段。這次以手寫字串重現解析邊界，將可接受的輸入收斂成「非空物件陣列，加上選擇性允許的一組編號後綴」。

##### 技術環境

範例使用 Node.js 的 JavaScript，函式同步接收字串、回傳陣列或拋出例外。不呼叫模型 API，也不連資料庫。輸入都是人工構造的測試資料，沒有把特定模型的回應格式當作保證。相同函式可以放在支援這些 JavaScript 語法的執行環境，欄位驗證仍由呼叫端負責。

##### 完整陣列後面，還有不能忽略的文字

依 [RFC 8259 的 JSON 語法](https://www.rfc-editor.org/rfc/rfc8259)，`1.3.3` 不符合數字格式。一份 JSON 值後面接另一組非空白文字，也不符合單份 JSON 文件的邊界。[MDN 的 JSON.parse 說明](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)指出，輸入不合 JSON 語法時會拋出 SyntaxError。只擷取第一個成功片段，會改變這個拒收條件。

##### 錯誤傳染鏈（時序）

```
測試字串 → 解析函式 → 呼叫端 → 資料庫
合法陣列＋未允許後綴 → 拋錯 → 不進入寫入階段 → 無寫入
合法陣列＋允許的編號 → 回傳 → 欄位驗證 → 驗證通過才寫入
本次探針止於函式回傳，資料庫並未連線。
```

解析成功只代表通過輸入邊界與元素型別檢查。日期、網址、必填欄位等業務條件仍可能不合格，回傳陣列不能直接視為可寫入資料。

##### 首項是 object，整份仍可能不合格

原本只檢查首項的寫法，會接受 `[null]`，也會漏掉 `[{"a":1},2]` 的第二項。[MDN 的 typeof 說明](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)列出 `typeof null` 為 object，因此補上非 null 條件，並逐項檢查。[Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) 則用來排除元素本身又是陣列的情況。

##### Code 對照：修法前後

修法前的最小反例，只涵蓋型別檢查缺口：

```
const arr = JSON.parse(block);
// BUG: null and later elements escape this check.
if (typeof arr[0] !== 'object') throw new Error('Rejected');
```

修法後從開頭掃到第一個閉合陣列，字串內的括號不參與深度計算。後綴必須全段符合白名單，其他文字一律拋錯。預設不允許編號後綴，只有已確認輸入契約需要此格式時才開啟選項。

```
function extractArray(text, { allowCitationSuffix = false } = {}) {
  const s = text.trim();
  if (!s.startsWith('[')) throw new Error('Expected array at start');
  let depth = 0, inString = false, escaped = false, end = -1;
  for (let i = 0; i < s.length; i++) {
    const c = s[i];
    if (inString) {
      if (escaped) escaped = false;
      else if (c === '\\') escaped = true;
      else if (c === '"') inString = false;
      continue;
    }
    if (c === '"') { inString = true; continue; }
    if (c === '[') depth++;
    if (c === ']') {
      depth--;
      if (depth === 0) { end = i + 1; break; }
    }
  }
  if (end < 0) throw new Error('Unclosed array');
  const tail = s.slice(end).trim();
  const citation = /^\[\s*\d+(?:\.\d+){2,}(?:\s*,\s*\d+(?:\.\d+){2,})*\s*,?\s*\]$/;
  // Any unrecognized suffix is an error, including a truncated second array.
  if (tail && !(allowCitationSuffix && citation.test(tail)))
    throw new Error('Unexpected suffix');
  const arr = JSON.parse(s.slice(0, end));
  if (!Array.isArray(arr) || arr.length === 0 ||
      !arr.every(x => x !== null && typeof x === 'object' && !Array.isArray(x)))
    throw new Error('Expected nonempty array of objects');
  return arr;
}
```

##### 多點編號與小數陣列的分界

後綴規則要求每個編號至少兩個小數點，所以 `[1.3]` 不會被當成引用略過。這是範例自行訂定的輸入契約，並非 Gemini 或其他模型的通用引用規格。只收資料陣列後的一組後綴，資料前的說明、Markdown 圍欄、第二份資料與未閉合尾段都拒收，避免靜默捨棄內容。

手寫探針已驗過正常物件、字串內括號與跳脫引號、巢狀欄位，以及 null、混合元素、空陣列、小數後綴和壞尾段。相同編號後綴在選項開啟時通過，關閉時拒收。驗證範圍只有這份函式與測試字串，沒有延伸成模型 API 或線上部署的結果。

##### 該被隔離的側效應類型

若接到資料寫入流程，以下是邊界設計條件，並非這次探針執行過的操作。解析失敗時不應進入寫入與派送階段，主資料已提交後的次要操作則各自記錄失敗，避免回應模糊造成重送。

- **事件紀錄**：稽核用途需與交易一致，診斷用途可獨立處理。
- **推播通知**：提交後派送，失敗保留重試資訊。
- **Webhook**：攜帶冪等識別，避免重送產生重複動作。
- **快取失效**：失敗須能追蹤過期資料風險。
- **搜尋索引**：更新延遲與主資料提交分開呈現。
- **分析事件**：不得把統計送出當作主資料成功證據。
- **非同步佇列**：需要可靠投遞時可評估交易式 outbox。

哪些紀錄必須跟主交易一起成功，取決於資料一致性要求。把所有例外吞掉，會把必要的稽核缺口藏起來。

##### 回到那段多出的中括號

結尾的 `[1.3.3]` 能否接受，取決於已訂明的輸入契約。這次修正把整段尾巴納入判定，物件陣列逐項檢查，壞片段不再因為前半段合法就被忽略。[Gemini 官方另提供結構化輸出設定](https://ai.google.dev/gemini-api/docs/structured-output)，可用 schema 約束回傳格式；內容值的業務驗證仍須保留。

— 邱柏宇

### JSON Arrays with Citation Suffixes: Keeping the Input Boundary Explicit

`[{"a":1}] [1.3.3]` resembles data followed by reference numbers, but parsing the entire string as JSON fails. Discarding every second bracket block can hide another payload or a truncated fragment. Hand-written inputs reproduced the boundary problem; the accepted contract became a nonempty array of objects with one optionally allowed reference suffix.

##### Technical Environment

The example runs synchronously in Node.js JavaScript. The function takes a string and either returns an array or throws. No model API or database is contacted. All inputs are synthetic fixtures, with no claim that any model guarantees this citation format.

##### Extra Text After a Complete Array Still Matters

[RFC 8259](https://www.rfc-editor.org/rfc/rfc8259) excludes multi-dot tokens such as `1.3.3` from JSON numbers. Non-whitespace after a JSON value also violates the boundary of a single JSON document. [MDN documents JSON.parse throwing SyntaxError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) for invalid JSON. Keeping only an initial valid fragment changes that rejection rule.

##### Error Propagation Sequence

```
Fixture → Parser → Caller → Database
Array + unapproved suffix → throw → no write stage → no write
Array + approved suffix → return → field validation → write only if valid
These probes stop at the function return; no database connection exists.
```

A returned array has passed the envelope and element-type checks. Required fields, dates and URLs can still fail application validation.

##### An Object in the First Slot Does Not Validate the Array

Checking only the first element accepts `[null]` and misses the second element of `[{"a":1},2]`. [MDN documents typeof null as object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof). The correction excludes null and checks every element; [Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) excludes arrays used as elements.

##### Code Diff: Before and After

The reduced before-example isolates the type-checking defect:

```
const arr = JSON.parse(block);
// BUG: null and later elements escape this check.
if (typeof arr[0] !== 'object') throw new Error('Rejected');
```

The corrected function scans from the start to the first closed array, ignoring brackets inside strings. Every remaining character must belong to the approved suffix. The option defaults to false and is enabled only for an explicitly agreed input contract.

```
function extractArray(text, { allowCitationSuffix = false } = {}) {
  const s = text.trim();
  if (!s.startsWith('[')) throw new Error('Expected array at start');
  let depth = 0, inString = false, escaped = false, end = -1;
  for (let i = 0; i < s.length; i++) {
    const c = s[i];
    if (inString) {
      if (escaped) escaped = false;
      else if (c === '\\') escaped = true;
      else if (c === '"') inString = false;
      continue;
    }
    if (c === '"') { inString = true; continue; }
    if (c === '[') depth++;
    if (c === ']') {
      depth--;
      if (depth === 0) { end = i + 1; break; }
    }
  }
  if (end < 0) throw new Error('Unclosed array');
  const tail = s.slice(end).trim();
  const citation = /^\[\s*\d+(?:\.\d+){2,}(?:\s*,\s*\d+(?:\.\d+){2,})*\s*,?\s*\]$/;
  // Any unrecognized suffix is an error, including a truncated second array.
  if (tail && !(allowCitationSuffix && citation.test(tail)))
    throw new Error('Unexpected suffix');
  const arr = JSON.parse(s.slice(0, end));
  if (!Array.isArray(arr) || arr.length === 0 ||
      !arr.every(x => x !== null && typeof x === 'object' && !Array.isArray(x)))
    throw new Error('Expected nonempty array of objects');
  return arr;
}
```

##### Dotted References and Decimal Arrays Have Different Boundaries

Each suffix token requires at least two dots, so `[1.3]` is rejected as a suffix. This is a local example contract, not a universal Gemini citation specification. Only one suffix after the data array is allowed; leading prose, Markdown fences, a second payload and incomplete trailing fragments are rejected.

Synthetic probes covered ordinary objects, brackets and escaped quotes in strings, nested fields, null, mixed elements, empty arrays, decimal suffixes and broken tails. The same reference suffix passed with the option enabled and failed with it disabled. These results cover the function and fixtures, without asserting model API behavior or a production deployment.

##### Side Effects That Should Be Isolated

The following conditions describe a possible write integration; none of these operations ran in the probes. Parse failures must stop writes and dispatch. Secondary operations after a primary commit need separate failure records so ambiguous responses do not cause duplicate submissions.

- **Event logs**: audit records may require transaction consistency; diagnostics can be separate.
- **Push notifications**: dispatch after commit and retain retry information.
- **Webhooks**: use idempotency identifiers against duplicate delivery.
- **Cache invalidation**: track the risk of stale reads after failure.
- **Search indexing**: distinguish indexing delay from primary commit status.
- **Analytics**: event delivery is no proof of a successful primary write.
- **Async queues**: consider a transactional outbox when reliable delivery is required.

Consistency requirements determine which records must succeed with the primary transaction. Swallowing every exception can conceal missing audit records.

##### Returning to the Extra Brackets

Accepting `[1.3.3]` depends on an explicit input contract. The correction checks the entire suffix and every object-array element, preventing a valid prefix from hiding a broken tail. [Gemini also offers schema-based structured output](https://ai.google.dev/gemini-api/docs/structured-output) to constrain response format; application validation of the values remains necessary.

— 邱柏宇
