How to Fix API JSON Malformed Request Body Error
In this tutorial, you'll learn about How to Fix API JSON Malformed Request Body Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your API client receives:
HTTP/1.1 400 Bad Request
Or:
{
"error": "invalid_json",
"message": "Request body contains malformed JSON"
}
The server cannot parse the request body as valid JSON due to a syntax error.
Quick Fix
1. Validate the JSON syntax
Use a JSON validator to find syntax errors:
# Validate JSON with python
echo '{"name": "John", "email": "john@example.com",}' | python3 -m json.tool
# Expected error: Expecting property name enclosed in double quotes
Common JSON syntax errors:
// Wrong — trailing comma
const body = JSON.stringify({ name: 'John', email: 'john@example.com', })
// Wrong — single quotes
const body = "{'name': 'John'}"
// Wrong — missing quotes on keys
const body = "{name: 'John'}"
// Wrong — unquoted string
const body = '{"name": John}'
// Right — valid JSON
const body = '{"name": "John", "email": "john@example.com"}'
2. Use JSON.stringify instead of manual strings
Always use JSON.stringify to build JSON bodies:
// Wrong — manual string concatenation
const body = '{"name":"' + name + '","email":"' + email + '"}'
// Right — use JSON.stringify
const body = JSON.stringify({ name, email })
3. Check the Content-Type header
The server may reject non-JSON bodies:
// Wrong — no Content-Type header
fetch('/api/users', {
method: 'POST',
body: JSON.stringify(data)
})
// Right — set Content-Type
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
4. Handle special characters
Strings with special characters must be properly escaped:
// Wrong — unescaped quotes in string
const data = { name: 'John "The Great" Doe' }
JSON.stringify(data)
// Result: '{"name":"John \"The Great\" Doe"}' — correctly escaped
// Wrong — unescaped control characters
const data = { name: 'John\nDoe' }
5. Check for encoding issues
UTF-8 BOM or wrong encoding can cause Parsing errors:
// Remove BOM if present
const response = await fetch('/api/data', {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
6. Log the raw request body for debugging
// Express.js — log raw body for debugging
app.use(express.json({
verify: (req, res, buf) => {
try {
JSON.parse(buf)
} catch (e) {
console.error('Malformed JSON:', buf.toString())
throw e
}
}
}))
Prevention
- Always use
JSON.stringifyto serialize request bodies. - Validate JSON with a linter before sending.
- Use API client libraries that handle Serialization automatically.
- Log malformed JSON bodies in development for debugging.
- Use a JSON schema validator for complex payloads.
Common Mistakes with json malformed
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro