A robust TypeScript/JavaScript library for parsing incomplete or partial JSON strings. Perfect for handling streaming JSON data where you need to parse the data before the full response arrives.
- ✅ Parse incomplete JSON strings
- ✅ Handle partial strings, objects, and arrays
- ✅ Support for nested structures
- ✅ Handle escaped characters properly
- ✅ Remove trailing commas automatically
- ✅ Support for all JSON data types (strings, numbers, booleans, null, objects, arrays)
- ✅ TypeScript support with full type definitions
- ✅ Zero dependencies
- ✅ Thoroughly tested
npm install partial-json-parserimport { parsePartialJson } from 'partial-json-parser';
// Incomplete string
parsePartialJson('{"animal":"do');
// Returns: { animal: "do" }
// Incomplete array
parsePartialJson('["dog","cat",');
// Returns: ["dog", "cat"]
// Incomplete nested structure
parsePartialJson('{"users":[{"name":"Alice","age":30},{"name":"Bob');
// Returns: { users: [{ name: "Alice", age: 30 }, { name: "Bob" }] }
// Streaming scenario
const chunks = [
'{"id',
'{"id":"123',
'{"id":"123","data',
'{"id":"123","data":"hello world'
];
chunks.forEach(chunk => {
const parsed = parsePartialJson(chunk);
console.log(parsed);
});
// Progressively outputs more complete objects as data arrivesParses a partial JSON string and returns a valid JavaScript object/array.
Parameters:
partialJson- An incomplete or complete JSON string
Returns:
- Parsed JavaScript value (object, array, string, number, boolean, or null)
- Returns
nullif the input is empty or unparseable
Example:
parsePartialJson('{"key":"value"'); // { key: "value" }
parsePartialJson('[1,2,3'); // [1, 2, 3]
parsePartialJson('{"nested":{"deep":"val'); // { nested: { deep: "val" } }Completes a partial JSON string by adding necessary closing characters.
Parameters:
partial- An incomplete JSON string
Returns:
- A valid, complete JSON string
Example:
completeJson('{"key":"val'); // '{"key":"val"}'
completeJson('["a","b"'); // '["a","b"]'Perfect for parsing streaming JSON responses from APIs (like OpenAI's ChatGPT):
const response = await fetch('https://api.example.com/stream');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Parse the incomplete JSON as it arrives
const parsed = parsePartialJson(buffer);
console.log(parsed); // Always get a valid object
}Handle partial JSON messages from WebSocket connections:
socket.on('message', (chunk) => {
buffer += chunk;
const parsed = parsePartialJson(buffer);
updateUI(parsed);
});The library uses a state machine to track:
- Whether it's currently inside a string
- Escape sequences within strings
- Open brackets and braces (stack-based tracking)
- Expected next tokens (keys, values, etc.)
When given partial JSON, it:
- Analyzes the string character by character
- Tracks the parse state (in string, in object, in array, etc.)
- Automatically closes any open structures
- Removes trailing commas
- Completes incomplete strings
- ✅ Incomplete strings:
{"name":"Joh→{"name":"Joh"} - ✅ Trailing commas:
["a","b",→["a","b"] - ✅ Escaped characters:
{"path":"C:\\User→{"path":"C:\\User"} - ✅ Nested structures:
{"a":{"b":{"c":1→{"a":{"b":{"c":1}}} - ✅ Incomplete keys:
{"a":1,"b→{"a":1} - ✅ Numbers:
{"count":42→{"count":42} - ✅ Booleans/null:
{"flag":tru→{"flag":null}
npm testThe library includes comprehensive tests covering:
- Incomplete strings, objects, and arrays
- Numbers, booleans, and null values
- Nested structures
- Escaped characters
- Real-world streaming scenarios
- Edge cases
MIT
Contributions are welcome! Please feel free to submit a Pull Request.