Open In App

How to Handle Newlines in JSON?

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Handling newlines in JSON is essential for maintaining data integrity when dealing with multiline text. JSON, being a text-based format, requires special consideration for newlines to ensure that text appears as intended across different platforms. Proper handling of newlines ensures consistent and accurate data representation in JSON files and during data transmission.

Syntax

'\\n'

About '\\n': The above syntax is used whenever we want to send data in multiple lines in a JSON format. Generally, it is difficult to send data in new lines from the server to the web. But by using this we can achieve the following requirement.

Using Escape Sequences (\n)

The escape sequence \n is used in JSON strings to represent newline characters, allowing text to span multiple lines. This approach keeps the JSON format intact while displaying the content as intended, making it useful for handling multiline data in JSON.

Example 1: In this example The \n in the JSON string represents a newline character. It creates line breaks within the string when displayed.

JavaScript
let json = '{\
    "companyInfo" : \
    "GeeksForGeeks\\n\\nOne stop solution for CS subjects"\
}';

let finalJson = JSON.parse(json);

console.log(finalJson.companyInfo); 

Output
GeeksForGeeks

One stop solution for CS subjects

Example 2: In this example we defines a JSON string with escaped newline characters. It parses the JSON string into an object and logs the details property, showing multi-line text in the console.

JavaScript
let student = '{"details": "P.V.Ramesh\\nC.S.E.\\nI.I.T. Hyderabad"}';

let finalJson = JSON.parse(student);

console.log(finalJson.details);

Output
P.V.Ramesh
C.S.E.
I.I.T. Hyderabad

Similar Reads