[PR #5894] fix(common): escape special characters in generated code snippets #5400

Open
opened 2026-03-17 02:50:57 +03:00 by kerem · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/hoppscotch/hoppscotch/pull/5894
Author: @danielalanbates
Created: 2/20/2026
Status: 🔄 Open

Base: mainHead: fix/issue-3011


📝 Commits (1)

  • cbed4c9 fix(common): escape special characters in generated code snippets (#3011)

📊 Changes

1 file changed (+69 additions, -2 deletions)

View changed files

📝 packages/hoppscotch-common/src/helpers/new-codegen/har.ts (+69 -2)

📄 Description

Summary

Fixes #3011

When a JSON request body contains values with special characters (newlines \n, tabs \t, backslashes \\, etc.), the Generate Code feature produces syntactically broken output for several target languages. For example, a Python requests snippet might embed a literal newline character inside a string literal instead of using the \n escape sequence.

Root cause

The code generation pipeline builds a HAR request object and passes it to @hoppscotch/httpsnippet. For JSON bodies, httpsnippet internally calls JSON.parse() on the body text — converting escape sequences like \n into actual control characters. Some code generators (Python requests, Rust reqwest, PHP curl, Swift nsurlsession, Objective-C nsurlsession) then embed these control characters literally into the generated code without re-escaping them.

Fix

In buildHarPostData (packages/hoppscotch-common/src/helpers/new-codegen/har.ts):

  • Added jsonHasProblematicChars() — recursively checks whether a parsed JSON body contains string values with control characters or backslashes
  • When such characters are detected, the HAR postData.mimeType is set to "text/plain" instead of "application/json". This prevents httpsnippet from parsing the body into a jsonObj and forces generators to use the raw text code path, which handles escaping correctly via JSON.stringify() or equivalent
  • The actual Content-Type header is preserved via buildHarHeaders(), so the generated code still sends application/json
  • JSON bodies without special characters continue to use the application/json path for idiomatic generated code (e.g. Python's json=payload)

Before / After

Body: {"content": "a=1\nprint(a+20)"}

Before (broken Python):

payload = { "content": "a=1
print(a+20)" }

After (valid Python):

payload = "{\"content\": \"a=1\\nprint(a+20)\"}"

Test plan

  • Verified fix produces valid generated code for Python requests, Shell cURL, JavaScript fetch, Rust reqwest, PHP cURL
  • Verified normal JSON bodies (without special characters) still use the idiomatic json=payload path
  • All pre-commit lint checks pass (0 errors)
  • Type checking passes
  • Manual test: open Hoppscotch, set a JSON body with \n in a string value, generate code in Python requests, verify the output is syntactically valid

This PR was created with the assistance of Claude Opus 4.6 by Anthropic. Happy to make any adjustments! Reviewed and submitted by a human.


Summary by cubic

Fixes broken generated code when JSON bodies contain special characters (e.g., \n, \t, \) across targets like Python, Rust, PHP, Swift, and Objective-C. Detects such bodies and uses the raw text path so characters are correctly escaped while preserving Content-Type: application/json.

  • Bug Fixes
    • Added jsonHasProblematicChars to flag control characters and backslashes in JSON.
    • When flagged, set HAR postData.mimeType to text/plain to avoid httpsnippet JSON parsing; headers still send application/json.
    • Clean JSON continues using the normal application/json path.

Written for commit cbed4c9665. Summary will update on new commits.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/hoppscotch/hoppscotch/pull/5894 **Author:** [@danielalanbates](https://github.com/danielalanbates) **Created:** 2/20/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/issue-3011` --- ### 📝 Commits (1) - [`cbed4c9`](https://github.com/hoppscotch/hoppscotch/commit/cbed4c966523417ea3140330285b8761a3109fde) fix(common): escape special characters in generated code snippets (#3011) ### 📊 Changes **1 file changed** (+69 additions, -2 deletions) <details> <summary>View changed files</summary> 📝 `packages/hoppscotch-common/src/helpers/new-codegen/har.ts` (+69 -2) </details> ### 📄 Description ## Summary Fixes #3011 When a JSON request body contains values with special characters (newlines `\n`, tabs `\t`, backslashes `\\`, etc.), the **Generate Code** feature produces syntactically broken output for several target languages. For example, a Python requests snippet might embed a literal newline character inside a string literal instead of using the `\n` escape sequence. ### Root cause The code generation pipeline builds a [HAR](http://www.softwareishard.com/blog/har-12-spec/) request object and passes it to `@hoppscotch/httpsnippet`. For JSON bodies, httpsnippet internally calls `JSON.parse()` on the body text — converting escape sequences like `\n` into actual control characters. Some code generators (Python `requests`, Rust `reqwest`, PHP `curl`, Swift `nsurlsession`, Objective-C `nsurlsession`) then embed these control characters literally into the generated code without re-escaping them. ### Fix In `buildHarPostData` (`packages/hoppscotch-common/src/helpers/new-codegen/har.ts`): - Added `jsonHasProblematicChars()` — recursively checks whether a parsed JSON body contains string values with control characters or backslashes - When such characters are detected, the HAR `postData.mimeType` is set to `"text/plain"` instead of `"application/json"`. This prevents httpsnippet from parsing the body into a `jsonObj` and forces generators to use the raw text code path, which handles escaping correctly via `JSON.stringify()` or equivalent - The actual `Content-Type` header is preserved via `buildHarHeaders()`, so the generated code still sends `application/json` - JSON bodies **without** special characters continue to use the `application/json` path for idiomatic generated code (e.g. Python's `json=payload`) ### Before / After **Body:** `{"content": "a=1\nprint(a+20)"}` **Before (broken Python):** ```python payload = { "content": "a=1 print(a+20)" } ``` **After (valid Python):** ```python payload = "{\"content\": \"a=1\\nprint(a+20)\"}" ``` ## Test plan - [x] Verified fix produces valid generated code for Python requests, Shell cURL, JavaScript fetch, Rust reqwest, PHP cURL - [x] Verified normal JSON bodies (without special characters) still use the idiomatic `json=payload` path - [x] All pre-commit lint checks pass (0 errors) - [x] Type checking passes - [ ] Manual test: open Hoppscotch, set a JSON body with `\n` in a string value, generate code in Python requests, verify the output is syntactically valid *This PR was created with the assistance of Claude Opus 4.6 by Anthropic. Happy to make any adjustments! Reviewed and submitted by a human.* <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Fixes broken generated code when JSON bodies contain special characters (e.g., \n, \t, \\) across targets like Python, Rust, PHP, Swift, and Objective-C. Detects such bodies and uses the raw text path so characters are correctly escaped while preserving Content-Type: application/json. - **Bug Fixes** - Added jsonHasProblematicChars to flag control characters and backslashes in JSON. - When flagged, set HAR postData.mimeType to text/plain to avoid httpsnippet JSON parsing; headers still send application/json. - Clean JSON continues using the normal application/json path. <sup>Written for commit cbed4c966523417ea3140330285b8761a3109fde. Summary will update on new commits.</sup> <!-- End of auto-generated description by cubic. --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/hoppscotch#5400
No description provided.