<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage如何存储JSON对象</title>
</head>
<body>
<script>
var obj = {
name: '徐同保',
job: 'web前端'
};
var objString = JSON.stringify(obj);
//setItem存储value
localStorage.setItem("obj", objString);
//getItem获取value
var objStringNew = localStorage.getItem('obj');
var objNew = JSON.parse(objString);
console.log('姓名:' + objNew.name);
console.log('职业:' + objNew.job);
</script>
</body>
</html>
也可以是数据对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage如何存储JSON对象</title>
</head>
<body>
<script>
var obj = [{
name: '徐同保',
job: 'web前端'
},
{
name: '徐同保s',
job: 'web前端s'
}
];
var objString = JSON.stringify(obj);
//setItem存储value
localStorage.setItem("obj", objString);
//getItem获取value
var objStringNew = localStorage.getItem('obj');
var objNew = JSON.parse(objString);
for (var i = 0; i < objNew.length; i++) {
console.log('姓名:' + objNew[i].name);
console.log('职业:' + objNew[i].job);
}
</script>
</body>
</html>