DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore
Results found: 

Question

How to format JSON string in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To format HSON string in JavaScript, use JSON.stringify() with some parameters. Following is the code −

Example

var details = {
   studentId: 101,
   studentFirstName: 'David',
   studentLastName: 'Miller',
   studentAge:21,
   subjectDetails: {
      subjectId: 'JavaScript_101',
      subjectName: 'Introduction to JavaScript',
   }
};
console.log("Not Pretty JSON Format=")
console.log(JSON.stringify(details));
console.log("Pretty JSON Format=")
console.log(JSON.stringify(details, null, 3));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo127.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo127.js
Not Pretty JSON Format=
{"studentId":101,"studentFirstName":"David","studentLastName":"Miller","studentAge":21,"subj
ectDetails":{"subjectId":"JavaScript_101","subjectName":"Introduction to JavaScript"}}
Pretty JSON Format={
   "studentId": 101,
   "studentFirstName": "David",
   "studentLastName": "Miller",
   "studentAge": 21,
   "subjectDetails": {
      "subjectId": "JavaScript_101",
      "subjectName": "Introduction to JavaScript"
   }
}
raja
Published on 10-Sep-2020 10:44:21
Advertisements

If you like, leave us your opinion

Was the article helpful and is it translated correctly?

Not affiliated with Tutorialspoint