{"id":13589604,"url":"https://github.com/mangiucugna/json_repair","last_synced_at":"2026-02-28T11:27:38.715Z","repository":{"id":193113832,"uuid":"688141049","full_name":"mangiucugna/json_repair","owner":"mangiucugna","description":"A python module to repair invalid JSON from LLMs","archived":false,"fork":false,"pushed_at":"2026-02-07T14:04:32.000Z","size":5538,"stargazers_count":4487,"open_issues_count":0,"forks_count":173,"subscribers_count":11,"default_branch":"main","last_synced_at":"2026-02-07T23:35:27.533Z","etag":null,"topics":["deep-learning","gpt-4","json","llama3","llm","machine-learning","mistral","openai-api","parser","repair"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/json-repair/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mangiucugna.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null},"funding":{"github":"mangiucugna"}},"created_at":"2023-09-06T18:28:42.000Z","updated_at":"2026-02-07T20:31:29.000Z","dependencies_parsed_at":"2023-11-07T13:37:12.943Z","dependency_job_id":"11d4a3ac-2d8a-41a1-896e-4902f1ce3cd8","html_url":"https://github.com/mangiucugna/json_repair","commit_stats":{"total_commits":283,"total_committers":11,"mean_commits":"25.727272727272727","dds":0.05653710247349819,"last_synced_commit":"919faae5cbf538ecdd12c99ecdb1cbb247441c12"},"previous_names":["mangiucugna/json_repair"],"tags_count":142,"template":false,"template_full_name":null,"purl":"pkg:github/mangiucugna/json_repair","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mangiucugna%2Fjson_repair","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mangiucugna%2Fjson_repair/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mangiucugna%2Fjson_repair/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mangiucugna%2Fjson_repair/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mangiucugna","download_url":"https://codeload.github.com/mangiucugna/json_repair/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mangiucugna%2Fjson_repair/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29327093,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-11T03:52:29.695Z","status":"ssl_error","status_checked_at":"2026-02-11T03:52:23.094Z","response_time":97,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","gpt-4","json","llama3","llm","machine-learning","mistral","openai-api","parser","repair"],"created_at":"2024-08-01T16:00:32.132Z","updated_at":"2026-02-28T11:27:38.684Z","avatar_url":"https://github.com/mangiucugna.png","language":"Python","funding_links":["https://github.com/sponsors/mangiucugna"],"categories":["cli","A01_文本生成_文本对话","Python","deep-learning","HarmonyOS","machine-learning","工具"],"sub_categories":["大语言对话模型及数据","Windows Manager"],"readme":"[![PyPI](https://img.shields.io/pypi/v/json-repair)](https://pypi.org/project/json-repair/)\n![Python version](https://img.shields.io/badge/python-3.10+-important)\n[![PyPI downloads](https://img.shields.io/pypi/dm/json-repair)](https://pypi.org/project/json-repair/)\n[![PyPI Downloads](https://static.pepy.tech/badge/json-repair)](https://pepy.tech/projects/json-repair)\n[![Github Sponsors](https://img.shields.io/github/sponsors/mangiucugna)](https://github.com/sponsors/mangiucugna)\n[![GitHub Repo stars](https://img.shields.io/github/stars/mangiucugna/json_repair?style=flat)](https://github.com/mangiucugna/json_repair/stargazers)\n\nEnglish | [中文](README.zh.md)\n\nThis simple package can be used to fix an invalid json string. To know all cases in which this package will work, check out the unit test.\n\n![banner](banner.png)\n\n---\n\n# Think about sponsoring this library!\nThis library is free for everyone and it's maintained and developed as a side project so, if you find this library useful for your work, consider becoming a sponsor via this link: https://github.com/sponsors/mangiucugna\n\n## Premium sponsors\n- [Icana-AI](https://github.com/Icana-AI) Makers of CallCoach, the world's best Call Centre AI Coach. Visit [https://www.icana.ai/](https://www.icana.ai/)\n- [mjharte](https://github.com/mjharte)\n\n---\n\n# Demo\nIf you are unsure if this library will fix your specific problem, or simply want your json validated online, you can visit the demo site on GitHub pages: https://mangiucugna.github.io/json_repair/\n\nOr hear an [audio deepdive generate by Google's NotebookLM](https://notebooklm.google.com/notebook/05312bb3-f6f3-4e49-a99b-bd51db64520b/audio) for an introduction to the module\n\n---\n\n# Motivation\nSome LLMs are a bit iffy when it comes to returning well formed JSON data, sometimes they skip a parentheses and sometimes they add some words in it, because that's what an LLM does.\nLuckily, the mistakes LLMs make are simple enough to be fixed without destroying the content.\n\nI searched for a lightweight python package that was able to reliably fix this problem but couldn't find any.\n\n*So I wrote one*\n\n# Supported use cases\n\n### Fixing Syntax Errors in JSON\n\n- Missing quotes, misplaced commas, unescaped characters, and incomplete key-value pairs.\n- Missing quotation marks, improperly formatted values (true, false, null), and repairs corrupted key-value structures.\n\n### Repairing Malformed JSON Arrays and Objects\n\n- Incomplete or broken arrays/objects by adding necessary elements (e.g., commas, brackets) or default values (null, \"\").\n- The library can process JSON that includes extra non-JSON characters like comments or improperly placed characters, cleaning them up while maintaining valid structure.\n\n### Auto-Completion for Missing JSON Values\n\n- Automatically completes missing values in JSON fields with reasonable defaults (like empty strings or null), ensuring validity.\n\n# How to use\n\nInstall the library with pip\n\n    pip install json-repair\n\nthen you can use use it in your code like this\n\n    from json_repair import repair_json\n\n    good_json_string = repair_json(bad_json_string)\n    # If the string was super broken this will return an empty string\n\n\nYou can use this library to completely replace `json.loads()`:\n\n    import json_repair\n\n    decoded_object = json_repair.loads(json_string)\n\nor just\n\n    import json_repair\n\n    decoded_object = json_repair.repair_json(json_string, return_objects=True)\n\n### Avoid this antipattern\nSome users of this library adopt the following pattern:\n\n    obj = {}\n    try:\n        obj = json.loads(string)\n    except json.JSONDecodeError as e:\n        obj = json_repair.loads(string)\n        ...\n\nThis is wasteful because `json_repair` will already verify for you if the JSON is valid, if you still want to do that then add `skip_json_loads=True` to the call as explained the section below.\n\n### Read json from a file or file descriptor\n\nJSON repair provides also a drop-in replacement for `json.load()`:\n\n    import json_repair\n\n    try:\n        file_descriptor = open(fname, 'rb')\n    except OSError:\n        ...\n\n    with file_descriptor:\n        decoded_object = json_repair.load(file_descriptor)\n\nand another method to read from a file:\n\n    import json_repair\n\n    try:\n        decoded_object = json_repair.from_file(json_file)\n    except OSError:\n        ...\n    except IOError:\n        ...\n\nKeep in mind that the library will not catch any IO-related exception and those will need to be managed by you\n\n### Non-Latin characters\n\nWhen working with non-Latin characters (such as Chinese, Japanese, or Korean), you need to pass `ensure_ascii=False` to `repair_json()` in order to preserve the non-Latin characters in the output.\n\nHere's an example using Chinese characters:\n\n    repair_json(\"{'test_chinese_ascii':'统一码'}\")\n\nwill return\n\n    {\"test_chinese_ascii\": \"\\u7edf\\u4e00\\u7801\"}\n\nInstead passing `ensure_ascii=False`:\n\n    repair_json(\"{'test_chinese_ascii':'统一码'}\", ensure_ascii=False)\n\nwill return\n\n    {\"test_chinese_ascii\": \"统一码\"}\n\n### JSON dumps parameters\n\nMore in general, `repair_json` will accept all parameters that `json.dumps` accepts and just pass them through (for example indent)\n\n### Performance considerations\nIf you find this library too slow because is using `json.loads()` you can skip that by passing `skip_json_loads=True` to `repair_json`. Like:\n\n    from json_repair import repair_json\n\n    good_json_string = repair_json(bad_json_string, skip_json_loads=True)\n\nI made a choice of not using any fast json library to avoid having any external dependency, so that anybody can use it regardless of their stack.\n\nSome rules of thumb to use:\n- Setting `return_objects=True` will always be faster because the parser returns an object already and it doesn't have serialize that object to JSON\n- `skip_json_loads` is faster only if you 100% know that the string is not a valid JSON\n- If you are having issues with escaping pass the string as **raw** string like: `r\"string with escaping\\\"\"`\n\n### Strict mode\n\nBy default `json_repair` does its best to “fix” input, even when the JSON is far from valid.  \nIn some scenarios you want the opposite behavior and need the parser to error out instead of repairing; pass `strict=True` to `repair_json`, `loads`, `load`, or `from_file` to enable that mode:\n\n```\nfrom json_repair import repair_json\n\nrepair_json(bad_json_string, strict=True)\n```\n\nThe CLI exposes the same behavior with `json_repair --strict input.json` (or piping data via stdin).\n\nIn strict mode the parser raises `ValueError` as soon as it encounters structural issues such as duplicate keys, missing `:` separators, empty keys/values introduced by stray commas, multiple top-level elements, or other ambiguous constructs. This is useful when you just need validation with friendlier error messages while still benefiting from json_repair’s resilience elsewhere in your stack.\n\nStrict mode still honors `skip_json_loads=True`; combining them lets you skip the initial `json.loads` check but still enforce strict parsing rules.\n\n### Schema-guided repairs\n\n**Alpha feature (not yet stable).** Schema-guided repairs are currently considered in alpha: The API and behavior may change or break between releases.\n\nYou can guide repairs with a JSON Schema (or a Pydantic v2 model). When enabled, the parser will:\n\n- Fill missing values (defaults, required fields).\n- Coerce scalars where safe (e.g., `\"1\"` → `1` for integer fields).\n- Drop properties/items that the schema disallows.\n\nThis is especially useful when you need deterministic, schema-valid outputs for downstream validation, storage, or typed processing. If the input cannot be repaired to satisfy the schema, `json_repair` raises `ValueError`.\n\nInstall the optional dependencies:\n\n    pip install 'json-repair[schema]'\n\n(For CLI usage, you can also use `pipx install 'json-repair[schema]'`.)\n\nWhen `schema` is provided, schema guidance is always applied (for both valid and invalid JSON). Schema guidance is mutually exclusive with `strict=True`.\n\n```\nfrom json_repair import repair_json\n\nschema = {\n    \"type\": \"object\",\n    \"properties\": {\"value\": {\"type\": \"integer\"}},\n    \"required\": [\"value\"],\n}\n\nrepair_json('{\"value\": \"1\"}', schema=schema, return_objects=True)\n```\n\nPydantic v2 model example:\n\n```\nfrom pydantic import BaseModel, Field\nfrom json_repair import repair_json\n\n\nclass Payload(BaseModel):\n    value: int\n    tags: list[str] = Field(default_factory=list)\n\n\nrepair_json(\n    '{\"value\": \"1\", \"tags\": }',\n    schema=Payload,\n    skip_json_loads=True,\n    return_objects=True,\n)\n```\n\n### Use json_repair with streaming\n\nSometimes you are streaming some data and want to repair the JSON coming from it. Normally this won't work but you can pass `stream_stable` to `repair_json()` or `loads()` to make it work:\n\n```\nstream_output = repair_json(stream_input, stream_stable=True)\n```\n\n### Use json_repair from CLI\n\nInstall the library for command-line with:\n```\npipx install json-repair\n```\nto know all options available:\n```\n$ json_repair -h\nusage: json_repair [-h] [-i] [-o TARGET] [--ensure_ascii] [--indent INDENT]\n                   [--skip-json-loads] [--schema SCHEMA] [--schema-model MODEL]\n                   [--strict] [filename]\n\nRepair and parse JSON files.\n\npositional arguments:\n  filename              The JSON file to repair (if omitted, reads from stdin)\n\noptions:\n  -h, --help            show this help message and exit\n  -i, --inline          Replace the file inline instead of returning the output to stdout\n  -o TARGET, --output TARGET\n                        If specified, the output will be written to TARGET filename instead of stdout\n  --ensure_ascii        Pass ensure_ascii=True to json.dumps()\n  --indent INDENT       Number of spaces for indentation (Default 2)\n  --skip-json-loads     Skip initial json.loads validation\n  --schema SCHEMA       Path to a JSON Schema file that guides repairs\n  --schema-model MODEL  Pydantic v2 model in 'module:ClassName' form that guides repairs\n  --strict              Raise on duplicate keys, missing separators, empty keys/values, and similar structural issues instead of repairing them\n```\n\n## Adding to requirements\n**Please pin this library only on the major version!**\n\nWe use TDD and strict semantic versioning, there will be frequent updates and no breaking changes in minor and patch versions.\nTo ensure that you only pin the major version of this library in your `requirements.txt`, specify the package name followed by the major version and a wildcard for minor and patch versions. For example:\n\n    json_repair==0.*\n\nIn this example, any version that starts with `0.` will be acceptable, allowing for updates on minor and patch versions.\n\n---\n# How to cite\nIf you are using this library in your academic work (as I know many folks are) please find the BibTex here:\n\n    @software{Baccianella_JSON_Repair_-_2025,\n        author  = \"Stefano {Baccianella}\",\n        month   = \"feb\",\n        title   = \"JSON Repair - A python module to repair invalid JSON, commonly used to parse the output of LLMs\",\n        url     = \"https://github.com/mangiucugna/json_repair\",\n        version = \"0.39.1\",\n        year    = 2025\n    }\n\nThank you for citing my work and please send me a link to the paper if you can!\n\n---\n\n# How it works\nThis module will parse the JSON file following the BNF definition:\n\n    \u003cjson\u003e ::= \u003cprimitive\u003e | \u003ccontainer\u003e\n\n    \u003cprimitive\u003e ::= \u003cnumber\u003e | \u003cstring\u003e | \u003cboolean\u003e\n    ; Where:\n    ; \u003cnumber\u003e is a valid real number expressed in one of a number of given formats\n    ; \u003cstring\u003e is a string of valid characters enclosed in quotes\n    ; \u003cboolean\u003e is one of the literal strings 'true', 'false', or 'null' (unquoted)\n\n    \u003ccontainer\u003e ::= \u003cobject\u003e | \u003carray\u003e\n    \u003carray\u003e ::= '[' [ \u003cjson\u003e *(', ' \u003cjson\u003e) ] ']' ; A sequence of JSON values separated by commas\n    \u003cobject\u003e ::= '{' [ \u003cmember\u003e *(', ' \u003cmember\u003e) ] '}' ; A sequence of 'members'\n    \u003cmember\u003e ::= \u003cstring\u003e ': ' \u003cjson\u003e ; A pair consisting of a name, and a JSON value\n\nIf something is wrong (a missing parentheses or quotes for example) it will use a few simple heuristics to fix the JSON string:\n- Add the missing parentheses if the parser believes that the array or object should be closed\n- Quote strings or add missing single quotes\n- Adjust whitespaces and remove line breaks\n\nI am sure some corner cases will be missing, if you have examples please open an issue or even better push a PR\n\n# Contributing\nIf you want to contribute, start with `CONTRIBUTING.md` and read the Code Wiki writeup for a tour of the codebase and key entry points: https://codewiki.google/github.com/mangiucugna/json_repair\n\n# How to develop\nUse `uv` to set up the dev environment and run tooling:\n\n    uv sync --group dev\n    uv run pre-commit run --all-files\n    uv run pytest\n\nMake sure that the Github Actions running after pushing a new commit don't fail as well.\n\n# How to release\nYou will need owner access to this repository\n- Edit `pyproject.toml` and update the version number appropriately using `semver` notation\n- **Commit and push all changes to the repository before continuing or the next steps will fail**\n- Run `python -m build`\n- Create a new release in Github, making sure to tag all the issues solved and contributors. Create the new tag, same as the one in the build configuration\n- Once the release is created, a new Github Actions workflow will start to publish on Pypi, make sure it didn't fail\n---\n# Repair JSON in other programming languages\n- Typescript: https://github.com/josdejong/jsonrepair\n- Go: https://github.com/RealAlexandreAI/json-repair\n- Ruby: https://github.com/sashazykov/json-repair-rb\n- Rust: https://github.com/oramasearch/llm_json\n- R: https://github.com/cgxjdzz/jsonRepair\n- Java: https://github.com/du00cs/json-repairj\n---\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=mangiucugna/json_repair\u0026type=Date)](https://star-history.com/#mangiucugna/json_repair\u0026Date)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmangiucugna%2Fjson_repair","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmangiucugna%2Fjson_repair","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmangiucugna%2Fjson_repair/lists"}