Explain Codes LogoExplain Codes Logo

How do I handle newlines in JSON?

javascript
json-stringification
escape-characters
json-parsing
Nikita BarsukovbyNikita Barsukov·Jan 18, 2025
TLDR

To manage newlines in JSON, escape them with \\n.

{"message": "Hello there\\nHow you doin'?"}

When the JSON is parsed, the newline is preserved, causing the text to span two lines. Remember to escape other control characters and double-quotes, which are denoted as \\t, \\r, \\f, and \\" respectively.

Escaping special characters and quotations

In JSON, dealing with special characters appropriately is crucial. Just like newlines, characters like tab (\t), carriage return (\r), and form feed (\f) need to be escaped. Also, always escape double quotes with \\" inside JSON strings to maintain the correct format.

{"message": "Tabs: \\t, Newlines: \\n, Carriage Returns: \\r, Form Feeds: \\f"}

JSON within other languages often requires a technique called double-escaping. This is due to the need to escape these characters for the string in the host language and subsequently for the JSON itself. If not done correctly, the parsing can lead to syntax errors and unexpected behaviour.

Automating escapes via JSON.stringify

When converting your JavaScript objects to JSON, JSON.stringify() is a powerful tool to use. This built-in function conveniently handles escaping for you, saving you from potential human-induced errors.

let message = { text: "First line\nSecond line" }; let jsonMessage = JSON.stringify(message); // jsonMessage is now {"text":"First line\\nSecond line"} // This could be your autobiography!

Debugging and Correct Display of Data

When things get tough, console.log() can be a detective's magnifying glass, closely investigating and revealing the minutiae, including those elusive newline characters.

console.log("Line 1\nLine 2"); // Eureka! That's where the missing piece of your puzzle was! // Line 1 // Line 2

For displaying JSON with newlines in HTML, you can style your way out. Using CSS properties, such as white-space: pre-line or white-space: pre-wrap, you can maintain the textual presentation accurately, and those newlines won't even know what hit 'em.

Secure Parsing: JSON.parse is your friend

Bear in mind the friend-foe theory. Always befriend JSON.parse() and avoid using eval() for parsing JSON data. The eval technique opens the gates to potential security hazards, like executing arbitrary codes (yes, that's as bad as it sounds). On the other hand, JSON.parse() is not just the safe option but also correctly handles character escaping, newlines included!

Ensure JSON validity: It's all in the control characters

Your JSON needs to be precision-crafted to guarantee smooth parsing. Inserting control characters directly into JSON strings is like trying to force the wrong piece into your puzzle – a no-go. You must correctly escape control characters ranging from U+0000 to U+001F to prevent breaking the JSON format.

// Too many cooks spoil the broth: { "controlChar": "Value containing a form feed character: \u000C" } // Great chefs know their ingredients: { "controlChar": "Value containing a form feed character: \\f" }

And for the final stroke of genius: always escape the reverse solidus (backslash) with \\\\. This tidbit prevents malformed and unpredictable serialized JSON, leading to no more parsing errors.