How to handle newlines in JSON ?
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 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.
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.
Example 1: This example shows the above-described approach.
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: In this example, we will print a new line in JSON.
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
Please Login to comment...