10. JSON
序列化:stringify
官方文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
let a = {
name: "lrc",
year: "20",
info: {
tag: "swimmer"
}
}
let jsonContent = JSON.stringify(a, (key, value) => {
console.log(1, key, value);
return value;
}, 2)
console.log("")
console.log(jsonContent)
console.log("")
console.log(JSON.stringify(a))
</script>
</html>
解析JSON:parse
官方文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
let a = {
name: "lrc",
year: "20",
info: {
tag: "swimmer"
},
test: ""
}
jsonContent = JSON.stringify(a)
console.log("")
let parseContent = JSON.parse(jsonContent, (key, value) => {
console.log(1, key, value)
return value ? value : '默认值'
})
console.log("")
console.log(parseContent)
console.log("")
console.log(JSON.parse(jsonContent))
</script>
</html>