56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
import { test } from 'node:test';
|
|||
|
|
import assert from 'node:assert/strict';
|
||
|
|
import { extractJson } from '../src/lib/jsonExtract.js';
|
||
|
|
|
||
|
|
test('parses bare JSON', () => {
|
||
|
|
assert.deepEqual(extractJson('{"a":1}'), { a: 1 });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('parses fenced json block', () => {
|
||
|
|
const out = extractJson('Here is the review:\n```json\n{"verdict":"pass"}\n```\nDone.');
|
||
|
|
assert.deepEqual(out, { verdict: 'pass' });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('parses fenced block without language tag', () => {
|
||
|
|
assert.deepEqual(extractJson('```\n{"x": [1,2]}\n```'), { x: [1, 2] });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('parses object embedded in prose', () => {
|
||
|
|
const out = extractJson('Sure! The result is {"grade":"B","overall":82} as requested.');
|
||
|
|
assert.deepEqual(out, { grade: 'B', overall: 82 });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('handles braces inside strings', () => {
|
||
|
|
const out = extractJson('prefix {"detail":"if (x) { return; }","n":2} suffix');
|
||
|
|
assert.deepEqual(out, { detail: 'if (x) { return; }', n: 2 });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('handles escaped quotes inside strings', () => {
|
||
|
|
const out = extractJson('{"t":"she said \\"hi\\" {ok}"}');
|
||
|
|
assert.deepEqual(out, { t: 'she said "hi" {ok}' });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('strips think blocks', () => {
|
||
|
|
const out = extractJson('<think>{"draft":true} reasoning</think>{"final":true}');
|
||
|
|
assert.deepEqual(out, { final: true });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('repairs trailing commas', () => {
|
||
|
|
assert.deepEqual(extractJson('{"a":1,"b":[1,2,],}'), { a: 1, b: [1, 2] });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('skips broken object and finds later valid one', () => {
|
||
|
|
const out = extractJson('{"broken": nope} then {"ok":1}');
|
||
|
|
assert.deepEqual(out, { ok: 1 });
|
||
|
|
});
|
||
|
|
|
||
|
|
test('returns null for no JSON', () => {
|
||
|
|
assert.equal(extractJson('no json here'), null);
|
||
|
|
assert.equal(extractJson(''), null);
|
||
|
|
assert.equal(extractJson(null), null);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('returns null for top-level array', () => {
|
||
|
|
assert.equal(extractJson('[1,2,3]'), null);
|
||
|
|
});
|