How to Minify JSON to a Single-Line String
JSON Stringify
When to Stringify JSON
Minify JSON when sending compact payloads to APIs, storing configuration in environment variables, reducing log size, or embedding JSON in script tags and CSV fields.
Real-World Examples
Multi-line config → single line for JSON.stringify in environment variables
Formatted API fixture → compact string for unit test snapshots
{"ok":true,"count":42} ready for HTTP request bodies
Common Mistakes
- Stringifying already-minified JSON repeatedly (harmless but pointless)
- Embedding minified JSON in HTML without escaping
</script>sequences - Assuming key order is preserved — some parsers reorder keys
Edge Cases
undefinedvalues in JavaScript objects are omitted by JSON.stringify — not valid JSON values- NaN and Infinity are not valid JSON numbers
- Unicode and escaped characters remain escaped in output
Developer Tips
- JavaScript:
JSON.stringify(obj)for compact output - Use formatted JSON in repos; stringify only for transport/storage constraints
Frequently asked questions
Does stringify remove whitespace only?
Yes for valid JSON input. The parser normalizes the structure and re-emits a compact string without extra spaces.
Will key order change?
JSON.parse and JSON.stringify in JavaScript generally preserve insertion order for object keys, but do not rely on key order across languages.
Can I stringify invalid JSON?
No. Input must be valid JSON before it can be minified safely.