[Bug]: try_parse_json_object turns backslash escapes into spaces when valid JSON comes in a code fence or after a sentence
Maintainers usually reply within 5 days
Nobody has claimed this yet.
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 74/100
Research direction
Start in packages/graphrag/graphrag/query/llm/text_utils.py at try_parse_json_object, where the cut-out from the first { to the last } runs through the backslash .replace cleanup before any validity check. Run the reproduction script in the issue to confirm line1\nline2 comes back as line1 nline2, and check that GlobalSearch._parse_search_response in the global search search.py shows the same damage. Done means valid cut-out JSON keeps its escapes, invalid input still goes through the old cleanup and json_repair, and a regression test covers fenced and prefixed responses.
Written by the indexing model from the issue text.
Description
Do you need to file an issue?
- I have searched the existing issues and this bug is not already filed.
- My model is hosted on OpenAI or Azure. If not, please look at the "model providers" issue and don't file a new one here.
- I believe this is a legitimate bug, not just a question. If this is a question, please use the Discussions area.
Describe the bug
try_parse_json_object in packages/graphrag/graphrag/query/llm/text_utils.py first calls json.loads on the whole response. If the model wraps valid JSON in a markdown fence or puts a sentence before it, that call fails. The function then cuts out the text from the first { to the last } and runs a cleanup chain on it. One step of that chain is .replace("\\", " "). It runs before anything checks whether the cut-out text is already valid JSON.
So every escape inside a string value is broken, even though the cut-out text was valid:
\nbecomes a space and the letter n.line1\nline2comes back asline1 nline2.\"becomes a space and a quote.He said \"hi\" todaycomes back asHe said "hi " today.\\becomes two spaces.C:\\data\\x.txtcomes back asC: data x.txt.\t,\rand\u00e9are broken the same way.
The same JSON without the fence parses correctly, because the first json.loads succeeds.
This function parses model output in three query paths:
- the global search map step,
GlobalSearch._parse_search_response(thedescriptiontext of each key point) rate_relevancyin dynamic community selection- DRIFT,
DriftAction.search(theresponsetext andfollow_up_queries)
Map and DRIFT answers are markdown, so they often contain \n. A fenced map response is a real case: #1173 shows gemma2 on ollama returning the map response inside a ```json fence. Also, #2625 shows that response_format_json_object=True does not reach the model on main, and it reports that Qwen and Mistral on vLLM sometimes answer with prose around the JSON. I did not find a trace from OpenAI or Azure, so this mostly affects local and other non-JSON-mode providers.
Back in #801 a maintainer review asked for a json.loads check first, so valid JSON would skip the string cleanup (done in #834). That check only covers the whole response. It does not cover the object cut out of a fenced or prefixed response.
Steps to reproduce
No model is needed. With graphrag installed from main:
import json
from graphrag.query.llm.text_utils import try_parse_json_object
from graphrag.query.structured_search.global_search.search import GlobalSearch
BS = "\\"
raw = "```json\n" + '{"d": "line1' + BS + 'nline2"}' + "\n```"
expected = json.loads(raw[raw.index("{") : raw.rindex("}") + 1])
_, got = try_parse_json_object(raw, verbose=False)
print("expected:", repr(expected))
print("got: ", repr(got))
map_raw = (
"```json\n"
+ '{"points": [{"description": "first line' + BS + 'nsecond line, said '
+ BS + '"ok' + BS + '"", "score": 80}]}'
+ "\n```"
)
print(GlobalSearch._parse_search_response(None, map_raw))
Expected Behavior
When the cut-out object is already valid JSON, it should be returned as parsed. The cleanup and json_repair should only run when it is not valid.
Expected output:
expected: {'d': 'line1\nline2'}
got: {'d': 'line1\nline2'}
[{'answer': 'first line\nsecond line, said "ok"', 'score': 80}]
GraphRAG Config Used
# Not needed. The reproduction calls the parser directly and uses no settings file.
Logs and screenshots
Output on main:
expected: {'d': 'line1\nline2'}
got: {'d': 'line1 nline2'}
[{'answer': 'first line nsecond line, said "ok "', 'score': 80}]
Additional Information
- GraphRAG Version: 3.3.0 (main at 34b2b67)
- Operating System: Windows 11
- Python Version: 3.13
- Related Issues: #1173 (fenced map response from gemma2 on ollama, fixed the regex then). #2625 (JSON mode is not sent to the model). Point 2 of #2625 also shows the backslash cleanup splitting single-quoted follow-up queries at
\'. That input is not valid JSON, so the fix below does not change it. - I have a small fix with a regression test. After the cut-out step it tries
json.loadsand returns the result when it is a non-empty dict. Everything else still goes through the old cleanup path. I will open a PR that references this issue.
Validated with Claude Opus 5.5.
- Dominant language
- Python
- Stars
- 36.6k
- Forks
- 3.9k
- Avg merge
- 4d 11h
- Merged PRs (30d)
- 1
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from microsoft/graphrag
-
[Bug]: response_format_json_object=True is silently dropped, so JSON mode never reaches the modelOpenbug triage
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
microsoft/graphrag#2625 · 1 comment ·
Maintainers usually reply within 5 days
-
Difficulty 1/5 Under an hour Newbie friendliness 95/100
Maintainers usually reply within 5 days
-
[Bug]: JsonCache.get() crashes with unhandled AttributeError on non-dict or invalid envelope JSON payloadsMay be free again A pull request for this issue was closed without being merged. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
microsoft/graphrag#2614 · 2 comments ·
Maintainers usually reply within 5 days
-
[Bug]: JSONLinesFileReader drops rows containing U+2028, U+2029 or U+0085 (uses str.splitlines)Open
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
microsoft/graphrag#2594 · 1 comment ·
Maintainers usually reply within 5 days
-
[Bug]: TokenChunker never terminates when chunking overlap >= size (no validation of size/overlap)Open
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
microsoft/graphrag#2593 · 2 comments ·
Maintainers usually reply within 5 days
All issues in microsoft/graphrag
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 64/100
FinanceFlash/unvibecode#819 ·
Maintainers usually reply within 1 day
-
documentation type/bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
add entry to blockOpen
Difficulty 1/5 Under an hour Newbie friendliness 65/100
StevenBlack/hosts#3299 ·
-
`garak --report` overwrites the input report when its name has no ".report"Possibly taken @0z5a claimed this today. Openneeds-triage
Difficulty 2/5 Half a day Newbie friendliness 72/100
Maintainers usually reply within 2 days
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 2 days