@isdk/json-repair 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.cn.md +2 -1
- package/README.md +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +1 -1
- package/docs/README.md +1 -0
- package/docs/_media/README.cn.md +2 -1
- package/docs/classes/RepairParser.md +3 -3
- package/docs/classes/SchemaWalker.md +5 -5
- package/docs/functions/jsonRepair.md +1 -1
- package/docs/interfaces/RepairOptions.md +5 -5
- package/docs/type-aliases/JSONPath.md +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
|
|
4
4
|
|
|
5
|
+
## [0.1.2](https://github.com/isdk/json-repair.js/compare/v0.1.1...v0.1.2) (2026-01-30)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
### Features
|
|
9
|
+
|
|
10
|
+
* support balanced delimiter tracking in greedy capture ([51ba9c9](https://github.com/isdk/json-repair.js/commit/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e))
|
|
11
|
+
|
|
5
12
|
## 0.1.1 (2026-01-30)
|
|
6
13
|
|
|
7
14
|
|
package/README.cn.md
CHANGED
|
@@ -24,6 +24,7 @@ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括
|
|
|
24
24
|
|
|
25
25
|
- **Schema 引导修复**:利用 Schema 解决歧义(例如通过判断冒号后面是否跟着 Schema 定义的 Key 来决定它是定界符还是字符串内容)。
|
|
26
26
|
- **贪婪字符串捕获**:智能捕获未加引号或破碎的字符串,直到遇到下一个合法的 Schema 键名。
|
|
27
|
+
- **平衡定界符追踪**:正确处理 DSL 风格字符串(如 `@func(a, b)`)内部嵌套在括号、方括号或花括号中的结构化符号(逗号、冒号等)。
|
|
27
28
|
- **“奇偶判定法”**:完美解决嵌套引号歧义(例如准确区分 `"A" OR "B"` 和 `"a"b"`)。
|
|
28
29
|
- **语义强制转换 (Coercion)**:
|
|
29
30
|
- **枚举模糊匹配**:如果 Schema 定义了枚举,能将 `"Processing!"` 自动匹配为 `"processing"`。
|
|
@@ -55,7 +56,7 @@ const schema = {
|
|
|
55
56
|
}
|
|
56
57
|
};
|
|
57
58
|
|
|
58
|
-
const brokenJson = '{ query: "python" OR "js", status:
|
|
59
|
+
const brokenJson = '{ query: "python" OR "js", status: Success! }';
|
|
59
60
|
|
|
60
61
|
const result = await jsonRepair(brokenJson, schema);
|
|
61
62
|
console.log(result);
|
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
|
|
|
24
24
|
|
|
25
25
|
- **Schema-Guided Repair**: Uses your Schema to resolve ambiguities (e.g., knowing if a colon marks a new key or is part of a string).
|
|
26
26
|
- **Greedy String Capture**: Intelligently captures unquoted or broken strings until the next valid Schema key.
|
|
27
|
+
- **Balanced Delimiter Tracking**: Correctly handles structural markers (commas, colons) inside parentheses, brackets, or braces within DSL-like strings (e.g., `@func(a, b)`).
|
|
27
28
|
- **The "Parity Rule"**: Solves nested quote ambiguity (e.g., correctly distinguishing between `"A" OR "B"` and `"a"b"`).
|
|
28
29
|
- **Semantic Coercion**:
|
|
29
30
|
- **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,s=Object.create,i=Object.defineProperty,h=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,r=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=(t,s,r,o)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let c of e(s))n.call(t,c)||c===r||i(t,c,{get:()=>s[c],enumerable:!(o=h(s,c))||o.enumerable});return t},c={};((t,s)=>{for(var h in s)i(t,h,{get:s[h],enumerable:!0})})(c,{RepairParser:()=>a,SchemaWalker:()=>f,jsonRepair:()=>l}),module.exports=(t=c,o(i({},"__esModule",{value:!0}),t));var u=((t,h,e)=>(e=null!=t?s(r(t)):{},o(!h&&t&&t.__esModule?e:i(e,"default",{value:t,enumerable:!0}),t)))(require("@apidevtools/json-schema-ref-parser"),1),f=class t{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(s){if(!s)return new t({});const i=new u.default,h=await i.dereference(s);return new t(h)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},a=class{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let e,r=!1;if('"'===t||"'"===t)try{e=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{e=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{e="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}if(r)return this.options.coerceTypes&&s?this.coerceValue(e,s):e;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const h=this.consumeValue();this.pos!==i&&(t.push(h),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=
|
|
1
|
+
"use strict";var t,s=Object.create,i=Object.defineProperty,h=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,r=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=(t,s,r,o)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let c of e(s))n.call(t,c)||c===r||i(t,c,{get:()=>s[c],enumerable:!(o=h(s,c))||o.enumerable});return t},c={};((t,s)=>{for(var h in s)i(t,h,{get:s[h],enumerable:!0})})(c,{RepairParser:()=>a,SchemaWalker:()=>f,jsonRepair:()=>l}),module.exports=(t=c,o(i({},"__esModule",{value:!0}),t));var u=((t,h,e)=>(e=null!=t?s(r(t)):{},o(!h&&t&&t.__esModule?e:i(e,"default",{value:t,enumerable:!0}),t)))(require("@apidevtools/json-schema-ref-parser"),1),f=class t{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(s){if(!s)return new t({});const i=new u.default,h=await i.dereference(s);return new t(h)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},a=class{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let e,r=!1;if('"'===t||"'"===t)try{e=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{e=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{e="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}if(r)return this.options.coerceTypes&&s?this.coerceValue(e,s):e;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const h=this.consumeValue();this.pos!==i&&(t.push(h),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=[];let i=!1,h="";for(;this.pos<this.input.length;){const e=this.peek();if(0===s.length&&this.isAtDelimiter())break;if(i){if(e===h){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===e||"'"===e)i=!0,h=e;else if("("===e||"["===e||"{"===e)s.push(e);else if(")"===e||"]"===e||"}"===e){const t=s[s.length-1];(")"===e&&"("===t||"]"===e&&"["===t||"}"===e&&"{"===t)&&s.pop()}t+=this.next()}let e=t.trim();if(e.length>=2){const t=e[0],s=e[e.length-1];if(('"'===t||"'"===t)&&t===s){const s=e.slice(1,-1);let i=0;for(let h=0;h<s.length;h++)s[h]!==t||0!==h&&"\\"===s[h-1]||i++;if(i%2==1||0===i)return s}}return e}isAtDelimiter(){if(this.pos>=this.input.length)return!0;const t=this.peek();if("}"===t||"]"===t)return!0;const s="number"==typeof this.pathStack[this.pathStack.length-1];if(","===t){if(s)return!0;const t=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(t)||this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)}if(this.isLookingAtKey(this.pathStack.slice(0,-1)))return!0;if(this.isWhitespace(t)){const t=this.pos;this.skipWhitespace();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isLookingAtKey(this.pathStack.slice(0,-1));return this.pos=t,i}return!1}isLookingAtKey(t,s=this.pos){const i=this.input.slice(s).match(/^\s*["']?([^"'\s:]+)["']?\s*:/);if(i){const s=i[1];return this.walker.isValidProperty(t,s)}return!1}coerceValue(t,s){const i=Array.isArray(s.type)?s.type:s.type?[s.type]:[],h=String(t).trim();if(s.enum){const t=h.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const e=null===t?"null":typeof t;if(i.length>0&&i.includes(e))return t;if(i.includes("number")||i.includes("integer")){let t=h.replace(/([^0-9.\-])/g,t=>","===t||","===t?"":" ").trim().split(/\s+/)[0];const s=parseFloat(t);if(!isNaN(s))return i.includes("integer")?Math.round(s):s}if(i.includes("boolean")){const t=h.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return i.includes("null")&&"null"===h.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}consumeNumber(){let t="";for(;this.pos<this.input.length&&/[0-9.\-]/.test(this.peek());)t+=this.next();return parseFloat(t)}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function l(t,s,i={}){const h=s instanceof f?s:await f.create(s);return new a(h,i).parse(t)}
|
package/dist/index.d.cts
CHANGED
|
@@ -122,6 +122,16 @@ declare class RepairParser {
|
|
|
122
122
|
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
123
123
|
* Implements the "Parity Rule" for smart quote stripping.
|
|
124
124
|
*/
|
|
125
|
+
/**
|
|
126
|
+
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
127
|
+
*
|
|
128
|
+
* This enhanced version tracks balanced delimiters (parentheses, brackets, braces) and quotes
|
|
129
|
+
* to ensure that structural markers (like commas or colons) inside DSL-like strings
|
|
130
|
+
* (e.g., `@weather(location="SH, CN")`) are correctly captured as part of the string.
|
|
131
|
+
*
|
|
132
|
+
* It also prioritizes top-level structural delimiters to prevent unescaped quotes from
|
|
133
|
+
* consuming the rest of the JSON.
|
|
134
|
+
*/
|
|
125
135
|
private consumeGreedyString;
|
|
126
136
|
/**
|
|
127
137
|
* Probes whether the current position marks a structural delimiter (end or next property).
|
package/dist/index.d.ts
CHANGED
|
@@ -122,6 +122,16 @@ declare class RepairParser {
|
|
|
122
122
|
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
123
123
|
* Implements the "Parity Rule" for smart quote stripping.
|
|
124
124
|
*/
|
|
125
|
+
/**
|
|
126
|
+
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
127
|
+
*
|
|
128
|
+
* This enhanced version tracks balanced delimiters (parentheses, brackets, braces) and quotes
|
|
129
|
+
* to ensure that structural markers (like commas or colons) inside DSL-like strings
|
|
130
|
+
* (e.g., `@weather(location="SH, CN")`) are correctly captured as part of the string.
|
|
131
|
+
*
|
|
132
|
+
* It also prioritizes top-level structural delimiters to prevent unescaped quotes from
|
|
133
|
+
* consuming the rest of the JSON.
|
|
134
|
+
*/
|
|
125
135
|
private consumeGreedyString;
|
|
126
136
|
/**
|
|
127
137
|
* Probes whether the current position marks a structural delimiter (end or next property).
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"@apidevtools/json-schema-ref-parser";var s=class s{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(i){if(!i)return new s({});const h=new t,
|
|
1
|
+
import t from"@apidevtools/json-schema-ref-parser";var s=class s{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(i){if(!i)return new s({});const h=new t,e=await h.dereference(i);return new s(e)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},i=class{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let e,r=!1;if('"'===t||"'"===t)try{e=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{e=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{e="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}if(r)return this.options.coerceTypes&&s?this.coerceValue(e,s):e;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const h=this.consumeValue();this.pos!==i&&(t.push(h),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=[];let i=!1,h="";for(;this.pos<this.input.length;){const e=this.peek();if(0===s.length&&this.isAtDelimiter())break;if(i){if(e===h){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===e||"'"===e)i=!0,h=e;else if("("===e||"["===e||"{"===e)s.push(e);else if(")"===e||"]"===e||"}"===e){const t=s[s.length-1];(")"===e&&"("===t||"]"===e&&"["===t||"}"===e&&"{"===t)&&s.pop()}t+=this.next()}let e=t.trim();if(e.length>=2){const t=e[0],s=e[e.length-1];if(('"'===t||"'"===t)&&t===s){const s=e.slice(1,-1);let i=0;for(let h=0;h<s.length;h++)s[h]!==t||0!==h&&"\\"===s[h-1]||i++;if(i%2==1||0===i)return s}}return e}isAtDelimiter(){if(this.pos>=this.input.length)return!0;const t=this.peek();if("}"===t||"]"===t)return!0;const s="number"==typeof this.pathStack[this.pathStack.length-1];if(","===t){if(s)return!0;const t=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(t)||this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)}if(this.isLookingAtKey(this.pathStack.slice(0,-1)))return!0;if(this.isWhitespace(t)){const t=this.pos;this.skipWhitespace();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isLookingAtKey(this.pathStack.slice(0,-1));return this.pos=t,i}return!1}isLookingAtKey(t,s=this.pos){const i=this.input.slice(s).match(/^\s*["']?([^"'\s:]+)["']?\s*:/);if(i){const s=i[1];return this.walker.isValidProperty(t,s)}return!1}coerceValue(t,s){const i=Array.isArray(s.type)?s.type:s.type?[s.type]:[],h=String(t).trim();if(s.enum){const t=h.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const e=null===t?"null":typeof t;if(i.length>0&&i.includes(e))return t;if(i.includes("number")||i.includes("integer")){let t=h.replace(/([^0-9.\-])/g,t=>","===t||","===t?"":" ").trim().split(/\s+/)[0];const s=parseFloat(t);if(!isNaN(s))return i.includes("integer")?Math.round(s):s}if(i.includes("boolean")){const t=h.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return i.includes("null")&&"null"===h.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}consumeNumber(){let t="";for(;this.pos<this.input.length&&/[0-9.\-]/.test(this.peek());)t+=this.next();return parseFloat(t)}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function h(t,h,e={}){const r=h instanceof s?h:await s.create(h);return new i(r,e).parse(t)}export{i as RepairParser,s as SchemaWalker,h as jsonRepair};
|
package/docs/README.md
CHANGED
|
@@ -28,6 +28,7 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
|
|
|
28
28
|
|
|
29
29
|
- **Schema-Guided Repair**: Uses your Schema to resolve ambiguities (e.g., knowing if a colon marks a new key or is part of a string).
|
|
30
30
|
- **Greedy String Capture**: Intelligently captures unquoted or broken strings until the next valid Schema key.
|
|
31
|
+
- **Balanced Delimiter Tracking**: Correctly handles structural markers (commas, colons) inside parentheses, brackets, or braces within DSL-like strings (e.g., `@func(a, b)`).
|
|
31
32
|
- **The "Parity Rule"**: Solves nested quote ambiguity (e.g., correctly distinguishing between `"A" OR "B"` and `"a"b"`).
|
|
32
33
|
- **Semantic Coercion**:
|
|
33
34
|
- **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
|
package/docs/_media/README.cn.md
CHANGED
|
@@ -24,6 +24,7 @@ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括
|
|
|
24
24
|
|
|
25
25
|
- **Schema 引导修复**:利用 Schema 解决歧义(例如通过判断冒号后面是否跟着 Schema 定义的 Key 来决定它是定界符还是字符串内容)。
|
|
26
26
|
- **贪婪字符串捕获**:智能捕获未加引号或破碎的字符串,直到遇到下一个合法的 Schema 键名。
|
|
27
|
+
- **平衡定界符追踪**:正确处理 DSL 风格字符串(如 `@func(a, b)`)内部嵌套在括号、方括号或花括号中的结构化符号(逗号、冒号等)。
|
|
27
28
|
- **“奇偶判定法”**:完美解决嵌套引号歧义(例如准确区分 `"A" OR "B"` 和 `"a"b"`)。
|
|
28
29
|
- **语义强制转换 (Coercion)**:
|
|
29
30
|
- **枚举模糊匹配**:如果 Schema 定义了枚举,能将 `"Processing!"` 自动匹配为 `"processing"`。
|
|
@@ -55,7 +56,7 @@ const schema = {
|
|
|
55
56
|
}
|
|
56
57
|
};
|
|
57
58
|
|
|
58
|
-
const brokenJson = '{ query: "python" OR "js", status:
|
|
59
|
+
const brokenJson = '{ query: "python" OR "js", status: Success! }';
|
|
59
60
|
|
|
60
61
|
const result = await jsonRepair(brokenJson, schema);
|
|
61
62
|
console.log(result);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
# Class: RepairParser
|
|
8
8
|
|
|
9
|
-
Defined in: [parser.ts:8](https://github.com/isdk/json-repair.js/blob/
|
|
9
|
+
Defined in: [parser.ts:8](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/parser.ts#L8)
|
|
10
10
|
|
|
11
11
|
A state-machine based parser that repairs and extracts structured data from broken JSON strings.
|
|
12
12
|
It uses a JSON Schema to guide the parsing process, especially for handling ambiguous or missing syntax.
|
|
@@ -17,7 +17,7 @@ It uses a JSON Schema to guide the parsing process, especially for handling ambi
|
|
|
17
17
|
|
|
18
18
|
> **new RepairParser**(`walker`, `options`): `RepairParser`
|
|
19
19
|
|
|
20
|
-
Defined in: [parser.ts:21](https://github.com/isdk/json-repair.js/blob/
|
|
20
|
+
Defined in: [parser.ts:21](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/parser.ts#L21)
|
|
21
21
|
|
|
22
22
|
Creates a new RepairParser instance.
|
|
23
23
|
|
|
@@ -45,7 +45,7 @@ Configuration options for the repair process.
|
|
|
45
45
|
|
|
46
46
|
> **parse**(`input`): `any`
|
|
47
47
|
|
|
48
|
-
Defined in: [parser.ts:35](https://github.com/isdk/json-repair.js/blob/
|
|
48
|
+
Defined in: [parser.ts:35](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/parser.ts#L35)
|
|
49
49
|
|
|
50
50
|
Parses the input string and returns the repaired JavaScript object.
|
|
51
51
|
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
# Class: SchemaWalker
|
|
8
8
|
|
|
9
|
-
Defined in: [walker/schema-walker.ts:8](https://github.com/isdk/json-repair.js/blob/
|
|
9
|
+
Defined in: [walker/schema-walker.ts:8](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/walker/schema-walker.ts#L8)
|
|
10
10
|
|
|
11
11
|
Navigates through a JSON Schema based on a JSON Path.
|
|
12
12
|
Handles $ref resolution and provides type information for specific paths.
|
|
@@ -17,7 +17,7 @@ Handles $ref resolution and provides type information for specific paths.
|
|
|
17
17
|
|
|
18
18
|
> **getExpectedTypes**(`path`, `key`): `string`[]
|
|
19
19
|
|
|
20
|
-
Defined in: [walker/schema-walker.ts:89](https://github.com/isdk/json-repair.js/blob/
|
|
20
|
+
Defined in: [walker/schema-walker.ts:89](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/walker/schema-walker.ts#L89)
|
|
21
21
|
|
|
22
22
|
Gets the expected types for a specific property at a given path.
|
|
23
23
|
|
|
@@ -47,7 +47,7 @@ An array of expected type strings (e.g., ["string", "number"]).
|
|
|
47
47
|
|
|
48
48
|
> **getSchemaForPath**(`path`): `any`
|
|
49
49
|
|
|
50
|
-
Defined in: [walker/schema-walker.ts:37](https://github.com/isdk/json-repair.js/blob/
|
|
50
|
+
Defined in: [walker/schema-walker.ts:37](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/walker/schema-walker.ts#L37)
|
|
51
51
|
|
|
52
52
|
Retrieves the sub-schema for a given JSON path.
|
|
53
53
|
|
|
@@ -71,7 +71,7 @@ The sub-schema at the specified path, or undefined if not found.
|
|
|
71
71
|
|
|
72
72
|
> **isValidProperty**(`path`, `key`): `boolean`
|
|
73
73
|
|
|
74
|
-
Defined in: [walker/schema-walker.ts:64](https://github.com/isdk/json-repair.js/blob/
|
|
74
|
+
Defined in: [walker/schema-walker.ts:64](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/walker/schema-walker.ts#L64)
|
|
75
75
|
|
|
76
76
|
Determines if a property key is valid for the given path according to the Schema.
|
|
77
77
|
|
|
@@ -101,7 +101,7 @@ True if the property is defined in the Schema or allowed by additionalProperties
|
|
|
101
101
|
|
|
102
102
|
> `static` **create**(`schema`): `Promise`\<`SchemaWalker`\>
|
|
103
103
|
|
|
104
|
-
Defined in: [walker/schema-walker.ts:22](https://github.com/isdk/json-repair.js/blob/
|
|
104
|
+
Defined in: [walker/schema-walker.ts:22](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/walker/schema-walker.ts#L22)
|
|
105
105
|
|
|
106
106
|
Static factory method to create a SchemaWalker instance.
|
|
107
107
|
Asynchronously dereferences the provided JSON Schema.
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
> **jsonRepair**(`input`, `schema?`, `options?`): `Promise`\<`any`\>
|
|
10
10
|
|
|
11
|
-
Defined in: [repair.ts:21](https://github.com/isdk/json-repair.js/blob/
|
|
11
|
+
Defined in: [repair.ts:21](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/repair.ts#L21)
|
|
12
12
|
|
|
13
13
|
Repairs and parses a JSON string generated by an LLM, guided by a JSON Schema.
|
|
14
14
|
This is the main entry point for the library.
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
# Interface: RepairOptions
|
|
8
8
|
|
|
9
|
-
Defined in: [types.ts:4](https://github.com/isdk/json-repair.js/blob/
|
|
9
|
+
Defined in: [types.ts:4](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L4)
|
|
10
10
|
|
|
11
11
|
Options for the JSON repair process.
|
|
12
12
|
|
|
@@ -16,7 +16,7 @@ Options for the JSON repair process.
|
|
|
16
16
|
|
|
17
17
|
> `optional` **additionalProperties**: `"keep"` \| `"remove"`
|
|
18
18
|
|
|
19
|
-
Defined in: [types.ts:35](https://github.com/isdk/json-repair.js/blob/
|
|
19
|
+
Defined in: [types.ts:35](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L35)
|
|
20
20
|
|
|
21
21
|
Defines how to handle properties not defined in the Schema.
|
|
22
22
|
|
|
@@ -29,7 +29,7 @@ Defines how to handle properties not defined in the Schema.
|
|
|
29
29
|
|
|
30
30
|
> `optional` **coerceTypes**: `boolean`
|
|
31
31
|
|
|
32
|
-
Defined in: [types.ts:27](https://github.com/isdk/json-repair.js/blob/
|
|
32
|
+
Defined in: [types.ts:27](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L27)
|
|
33
33
|
|
|
34
34
|
Whether to attempt type coercion based on the Schema.
|
|
35
35
|
|
|
@@ -41,7 +41,7 @@ If `true`, the parser will try to convert values to the expected type (e.g., "12
|
|
|
41
41
|
|
|
42
42
|
> `optional` **keyMatching**: `boolean` \| (`key`, `properties`) => `string` \| `undefined`
|
|
43
43
|
|
|
44
|
-
Defined in: [types.ts:12](https://github.com/isdk/json-repair.js/blob/
|
|
44
|
+
Defined in: [types.ts:12](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L12)
|
|
45
45
|
|
|
46
46
|
Fuzzy matching for keys.
|
|
47
47
|
|
|
@@ -55,7 +55,7 @@ Fuzzy matching for keys.
|
|
|
55
55
|
|
|
56
56
|
> `optional` **stringCaptureStrategy**: `"conservative"` \| `"aggressive"`
|
|
57
57
|
|
|
58
|
-
Defined in: [types.ts:20](https://github.com/isdk/json-repair.js/blob/
|
|
58
|
+
Defined in: [types.ts:20](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L20)
|
|
59
59
|
|
|
60
60
|
Strategy for greedy string capture when standard JSON parsing fails.
|
|
61
61
|
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
> **JSONPath** = (`string` \| `number`)[]
|
|
10
10
|
|
|
11
|
-
Defined in: [types.ts:42](https://github.com/isdk/json-repair.js/blob/
|
|
11
|
+
Defined in: [types.ts:42](https://github.com/isdk/json-repair.js/blob/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e/src/types.ts#L42)
|
|
12
12
|
|
|
13
13
|
Represents the current path in a JSON structure.
|
|
14
14
|
A list of strings (keys) and numbers (indices).
|
package/package.json
CHANGED