How to handle newlines in JSON ?
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.
"GeeksForGeeks\\n\\nOne stop solution for CS subjects"
One stop solution for CS subjects
Example 2: In this example, we will print a new line in JSON.
let finalJson = JSON.parse(student);