3 回答
TA贡献2080条经验 获得超4个赞
JSON不是库,而是一种表示法。花一些时间来阅读它。
有一些编码方法。下面有一个简单的示例。
获取所有检查的输入及其值:
var result = Array.from(document.querySelectorAll('input[type=checkbox]:checked')).map(a => { return { id: a.getAttribute("id"), value: a.value }; });
console.log(result);
在本地存储中保存和从中检索:
var resultInJson = JSON.stringify(result);
console.log(resultInJson);
localStorage.setItem("data", resultInJson);
console.log(localStorage.getItem("data"));
console.log(JSON.parse(localStorage.getItem("data")));
TA贡献1797条经验 获得超6个赞
没有JSON注意事项的解决方案:
const
foodForm = document.querySelector('#food-form'),
StorageName = 'myFoodStorage';
foodForm.onchange=()=>{ // = storeFood
let CheckList = Array.from(foodForm.querySelectorAll('input[type=checkbox]')).map(a=>`${a.id}=${a.checked}`);
sessionStorage.setItem(StorageName, CheckList.join(','));
}
window.onload=()=>{ // = retrieveFood
let CheckList = sessionStorage.getItem(StorageName)
if (CheckList) {
CheckList.split(',').forEach(e=>{
let pair = e.split('=');
document.getElementById('pair[0]').checked = pair[1] === 'true';
})
}
}
TA贡献1876条经验 获得超5个赞
如果要更高级的序列化,请使用此方法,它应适用于所有值为字符串的对象。
用于sessionStorage.setItem('foods', serialize(foodStates))存储复选框的状态并用于对其parse(sessionStorage.getItem('foods'))进行重构
"use strict";
function sanitize(str) {
//Split into char array, escape chars and put back together into string
return str.split('').map(chr => sanitize.map[chr] || chr).join('')
}
function desanitize(str) {
//Split into char array, escape chars and put back together into string
return str.replace('\\:', ':').replace('\\;', ';').replace('\\\\', '\\')
}
sanitize.map = {
'\\': '\\\\',
':': '\\:',
';': '\\;'
}
function serialize(obj) {
var result = "";
for(var prop in obj) {
result += `${sanitize(prop)} :${sanitize(obj[prop])} ;`;
}
//Remove last ' ;'
result = result.slice(0, -2);
return result;
}
function parse(str) {
var obj = {};
for(var part of str.split(' ;')) {
var [key, value] = part.split(' :')
key = desanitize(key)
value = desanitize(value)
obj[key] = value;
}
return obj;
}
var orgObj = {pizza: "true", hamburger: "false", sandwich: "true"}
console.log(orgObj)
var encodedString = serialize(orgObj)
console.log(encodedString)
var newObj = parse(encodedString)
console.log(newObj)
添加回答
举报