Escape or unescape JSON strings for APIs, databases, and code. Handle special characters properly.
Character escaping is the process of converting special characters into a format that doesn't conflict with syntax. In JSON, certain characters have special meaning—quotes define strings, backslashes start escape sequences, newlines would break single-line strings. When you need these characters inside a JSON string value, they must be escaped.
For example, if you want a JSON string to contain a quote character: "He said \"Hello\"". The inner quotes are escaped as \" so the JSON parser knows they're part of the string content, not the end of the string. Without escaping, "He said "Hello""would cause a syntax error—the parser would think the string ends at the second quote.
JSON requires these characters to be escaped when used inside string values:
\" because quotes delimit strings\\\\ because backslash starts escape sequences\\n because JSON strings must be single-line\\r for the same reason\\t for consistent whitespace representation\\f (rarely used but part of JSON spec)\\b (also rare)Common Escape Sequences:
\\n - Newline (line feed)\\r - Carriage return\\t - Tab\\" - Double quote\\\\ - BackslashLess Common:
\\f - Form feed\\b - Backspace\\uXXXX - Unicode character\\/ - Forward slash (optional)For characters outside standard ASCII, JSON supports Unicode escape sequences: \\uXXXXwhere XXXX is the four-digit hexadecimal Unicode code point. For example:
\\u00A9 represents © (copyright symbol)\\u2764 represents ❤ (heart emoji)\\u4E2D represents 中 (Chinese character)Modern JSON parsers handle UTF-8 directly, so Unicode escaping is optional for most characters. However, it's useful for ensuring compatibility with systems that don't support UTF-8 or for representing control characters that can't be typed directly.
The most common use case for JSON escaping is embedding JSON within string literals in programming languages. When you assign JSON to a JavaScript string variable, you need to escape it so the JavaScript parser doesn't misinterpret the quotes:
// Without escaping - SYNTAX ERROR
const jsonStr = "{"name": "John"}"; // Breaks at first inner quote
// With escaping - CORRECT
const jsonStr = "{\"name\": \"John\"}"; // Properly escapedThis is why APIs returning JSON as strings (in error messages, logs, or nested responses) need escaping. Our tool automates this process so you don't have to manually add backslashes.
When you need to embed JSON data directly in HTML or JavaScript code, escaping is essential. Unescaped quotes would break the syntax. Common scenario: passing server data to client-side JavaScript.
<!-- Without escaping - BREAKS -->
<script>
const data = "{"name": "John", "role": "Developer"}";
</script>
<!-- With escaping - WORKS -->
<script>
const data = "{\"name\": \"John\", \"role\": \"Developer\"}";
const obj = JSON.parse(data);
</script>Modern frameworks (React, Vue, Angular) handle this automatically, but when writing vanilla JavaScript or server-rendered HTML, you need to escape JSON strings manually.
Storing or querying JSON in SQL databases requires proper escaping to prevent syntax errors and SQL injection. When inserting JSON into a VARCHAR column or using PostgreSQL's JSONB functions, quotes must be escaped.
-- Without escaping - SQL ERROR
INSERT INTO users (data) VALUES ('{"name": "John", "bio": "Developer at "Acme Corp""}');
-- With escaping - WORKS
INSERT INTO users (data) VALUES ('{"name": "John", "bio": "Developer at \"Acme Corp\""}');Most database libraries (like node-postgres, psycopg2, JDBC) handle escaping automatically when you use parameterized queries. But when building raw SQL strings, you must escape manually.
Passing JSON to command-line tools (cURL, CLIs, scripts) requires escaping because shells interpret quotes and special characters. Without escaping, the shell breaks the JSON into multiple arguments.
# Without escaping - Shell interprets quotes incorrectly
curl -X POST -d '{"name": "John", "message": "Hello "world""}' api.com/users
# With escaping - Works correctly
curl -X POST -d '{"name": "John", "message": "Hello \"world\""}' api.com/users
# Alternative: Use single quotes for outer string, double inside
curl -X POST -d '{"name": "John", "message": "Hello \"world\""}' api.com/usersWhen sending JSON as part of another JSON payload (nested JSON), the inner JSON must be escaped and sent as a string. Common in webhook configurations, dynamic queries, or meta-APIs.
{
"action": "create_user",
"payload": "{\"name\": \"John\", \"email\": \"john@example.com\"}"
}The outer JSON is properly formatted, but the payload value is an escaped JSON string that the receiving API will parse separately.
Template literals in JavaScript (backticks) preserve newlines and special characters, but when you need to embed those templates as JSON strings, escaping is required. Use escaping to convert multi-line template strings into valid JSON-encoded strings.
JavaScript provides JSON.stringify() for automatic escaping:
// Automatic escaping with JSON.stringify
const data = { name: "John", bio: 'Developer\nLoves "coding"' };
const jsonString = JSON.stringify(data);
console.log(jsonString);
// Output: {"name":"John","bio":"Developer\\nLoves \\"coding\\""}
// Embed in HTML attribute
const html = `<div data-user='${jsonString}'></div>`;
// Manual escaping function (if needed)
function escapeJson(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t');
}Python's json module handles escaping:
import json
# Automatic escaping
data = {"name": "John", "bio": "Developer\nLoves \"coding\""}
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "John", "bio": "Developer\\nLoves \\"coding\\""}
# Unescape JSON string
escaped = '{\"name\": \"John\"}'
unescaped = json.loads(f'"{escaped}"') # Wrap in quotes to parse as string
# Or use replace
unescaped = escaped.replace('\\"', '"').replace('\\\\', '\\')Java and C# use similar approaches with their JSON libraries:
Java (using Jackson):
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Map<String, String> data = Map.of(
"name", "John",
"bio", "Developer\nLoves \"coding\""
);
String jsonString = mapper.writeValueAsString(data);
System.out.println(jsonString);C# (using System.Text.Json):
using System.Text.Json;
var data = new {
name = "John",
bio = "Developer\nLoves \"coding\""
};
string jsonString = JsonSerializer.Serialize(data);
Console.WriteLine(jsonString);In bash scripts, use tools like jq for safe JSON manipulation:
#!/bin/bash
# Using jq to properly escape
name="John"
bio="Developer\nLoves \"coding\""
# jq handles escaping automatically
json=$(jq -n \
--arg name "$name" \
--arg bio "$bio" \
'{ name: $name, bio: $bio }')
echo "$json"
# Output: {"name":"John","bio":"Developer\nLoves \"coding\""}
# Send to API
curl -X POST -H "Content-Type: application/json" -d "$json" api.com/usersJSON escaping converts special characters in JSON strings to their escaped equivalents, making them safe to use in APIs, databases, and code. This is essential when embedding JSON inside other formats.
Escape JSON before sending in POST requests or storing in databases
Properly escape JSON before inserting into SQL VARCHAR or TEXT columns
Embed JSON safely in JavaScript string variables
Unescape JSON from log files for easier reading and debugging
Deepen your understanding of JSON string handling and programming techniques:
Complete guide to JSON escaping, parsing, and string manipulation in JS.
Handling JSON escaping and encoding in Python applications.
Troubleshooting escape sequence issues and character encoding problems.
Professional techniques for safe string handling and data validation.