要在JavaScript中格式化HSON字符串,请使用带有一些参数的JSON.stringify()。以下是代码-
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));
要运行以上程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo127.js。
输出结果
这将产生以下输出-
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" } }