如何在 JavaScript 中设置 JSON 字符串格式?
若要在 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" } }
广告