使用 JavaScript 去掉引號並轉換為 JSON 物件?
要做到這一點,你可以使用 replace() 與 parse()。以下程式碼演示瞭如何操作: -
示例
var studentDetails = `"{""name"": ""John"",""subjectName"": ""Introduction To JavaScript""}"`; console.log("The actual object="); console.log(studentDetails); var removeFirstAndLast = studentDetails.substring(1,studentDetails.length-1) var removeDoubleQuotes = removeFirstAndLast.replace(/""/gi, `"`) console.log(removeDoubleQuotes) var output = JSON.parse(removeDoubleQuotes); console.log(output);
要執行上述程式,你需要使用以下命令: -
node fileName.js.
此處我的檔名是 demo103.js。
輸出結果
這將產生以下輸出結果: -
PS C:\Users\Amit\JavaScript-code> node demo103.js The actual object= "{""name"": ""John"",""subjectName"": ""Introduction To JavaScript""}" {"name": "John","subjectName": "Introduction To JavaScript"} { name: 'John', subjectName: 'Introduction To JavaScript' }
廣告