Open In App
Related Articles

How to handle newlines in JSON ?

Improve Article
Save Article
Like Article

JSON is a language-independent data format. It is a JavaScript Object Notation. Basically, it is a text-based format used to represent structured data. Data is being sent in this format from the server to the client.

In this article, we will see how to approach or handle newlines in JSON.



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.


  • First, we need to declare a variable as “json1” and then we need to assign the JSON to it.
  • In JSON object make sure that you are having a sentence where you need to print in different lines.
  • Now in order to print the statements in different lines we need to use ‘\\n’ (backward slash).
  • As we now know the technique to print in newlines, now just add ‘\\n’ wherever you want.
  • Now, as it is a JSON we need to parse it in order to print it. So use JSON.parse() method and parse the JSON.
  • After completing the above steps write a console.log() statement to print the output.
  • Once you are done with it, execute the file to get the output.

Example 1: This example shows the above-described approach.


var json = '{
    "companyInfo" : 
    "GeeksForGeeks\\n\\nOne stop solution for CS subjects"
let finalJson=JSON.parse(json);



One stop solution for CS subjects

Example 2: In this example, we will print a new line in JSON.


var student = '{
    "details" : 
    "P.V.Ramesh\\nC.S.E.\\nI.I.T. Hyderabad"
let finalJson = JSON.parse(student);


I.I.T. Hyderabad
Last Updated : 11 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials