JS與JSON之間的格式轉換
語法:JSON.stringify()
儲存資料 Storing Data
Example:
Storing data in local storage
<body>
<h2>Store and retrieve data from local storage.</h2>
<p id="demo"></p>
<script>
// Storing data:
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script>
</body>
Array 轉換成 String
// .stringify() 陣列轉換JSON格式 / 陣列轉換成字串
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
console.log(typeof arr); //object
console.log(typeof myJSON); //string
字串化日期 Stringify Date
const obj = {name: "John", today: new Date(), city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
//result : {"name":"John","today":"2023-11-16T14:55:18.981Z","city":"New York"}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 kimfei2014@gmail.com