Skip to content

DevMaxC/partial-json-parser

Repository files navigation

Partial JSON Parser

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.

Features

  • ✅ 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

Installation

npm install partial-json-parser

Usage

import { 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 arrives

API

parsePartialJson(partialJson: string): any

Parses 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 null if 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" } }

completeJson(partial: string): string

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"]'

Use Cases

Streaming API Responses

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
}

WebSocket Messages

Handle partial JSON messages from WebSocket connections:

socket.on('message', (chunk) => {
  buffer += chunk;
  const parsed = parsePartialJson(buffer);
  updateUI(parsed);
});

How It Works

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:

  1. Analyzes the string character by character
  2. Tracks the parse state (in string, in object, in array, etc.)
  3. Automatically closes any open structures
  4. Removes trailing commas
  5. Completes incomplete strings

Edge Cases Handled

  • ✅ 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}

Testing

npm test

The 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

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published