Parse partial JSON generated by LLM
Low maintenance activity. Last release 12 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
Consider insteadjson-repairPythie’s Index: 8549.5M downloads/moCompare →
pip install partial-json-parserPartial JSON Parser
Sometimes we need LLM (Large Language Models) to produce structural information instead of natural language. The easiest way is to use JSON.
But before receiving the last token of response, the JSON is broken, which means you can't use JSON.parse to decode it. But we still want to stream the data to the user.
Here comes partial-json-parser, a lightweight and customizable library for parsing partial JSON strings. Here is a demo.
(Note that there is a JavaScript implementation too)
Installation
pip install partial-json-parser # or poetry / pdm / uv
partial-json-parser is implemented purely in Python, with good type hints. It is zero-dependency and works with Python 3.6+.
You can install run its demo playground by installing rich too or:
pip install partial-json-parser[playground]
Then run the json-playground in your terminal, and you can try the parser interactively.
Usage
from partial_json_parser import loads
>>> loads('{"key": "v') # {'key': 'v'}
Alternatively, you can use ensure_json to get the completed JSON string:
from partial_json_parser import ensure_json
>>> ensure_json('{"key": "v') # '{"key": "v"}'
Detailed Usage
You can import the loads function and the Allow object from the library like this:
from partial_json_parser import loads, Allow
The Allow object is just an Enum for options. It determines what types can be partial. types not included in allow only appears after its completion can be ensured.
Parsing complete / partial JSON strings
The loads function works just like the built-in json.loads when parsing a complete JSON string:
result = loads('{"key":"value"}')
print(result) # Outputs: {'key': 'value'}
You can parse a partial JSON string by passing an additional parameter to the loads function. This parameter is a of the constants from the flag: