Skip to content
Related Articles

Related Articles

How to handle newlines in JSON ?

View Discussion
Improve Article
Save Article
  • Last Updated : 11 Jan, 2021
View Discussion
Improve Article
Save 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.

Syntax: 

'\\n'

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

Approach:

  • 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.

Code implementation:

Example 1:

Javascript




var 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:

Javascript




var 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
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!