[英]unexpected token a in JSON at position 0 at JSON.parse
I am trying to save items in LocalStorage
by:我正在尝试通过以下方式将项目保存在
LocalStorage
中:
document.querySelector('form').addEventListener('submit', function(e){
e.preventDefault();
let input = document.getElementById('task').value;
let tasks;
if(localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.push(input);
localStorage.setItem('tasks', JSON.stringify(tasks))
})
This doesn't seem to be saving my values, and I get the error:这似乎没有保存我的值,我得到了错误:
Unexpected token a in JSON at position 0 at JSON.parse
Any help is appreciated!任何帮助表示赞赏!
Try clearing your localStorage and running your code again.尝试清除您的 localStorage 并再次运行您的代码。 If you had a previous value saved in there that was not a valid JSON-parsable object, it would never be over-ridden since your code would fail before that.
如果您在其中保存了一个不是有效的 JSON 可解析 object 的先前值,那么它将永远不会被覆盖,因为您的代码在此之前会失败。
If that does not work, try replacing localStorage
with window.localStorage
.如果这不起作用,请尝试将
localStorage
替换为window.localStorage
。
What I would do is the following:我会做的是以下几点:
var myjson = localStorage.getItem('tasks');
console.log(myjson);
if (myjson === null ) {
tasks = [];
} else{
tasks = JSON.parse(myjson);
}
Confirm myjson is a valid json object.确认 myjson 是有效的 json object。
You can use jsonlint to validate your json object.您可以使用jsonlint来验证您的 json object。
This might a problem in setting the local storage as well.这也可能是设置本地存储的问题。 Please make sure that the value that you are trying to set in the local storage is being saved.
请确保您尝试在本地存储中设置的值正在保存。
If the above is true then you can proceed with something like the below code:如果上述情况属实,那么您可以继续执行以下代码:
var objJson = localStorage.getItem('tasks');
objTasks = objJson ? JSON.parse(objJson) : [];
The above lines of code is going to make sure that the value for the local storage "tasks" is retrieved and if its retrieved and the value isn't null and not empty then and then only it will get parsed.上面的代码行将确保检索本地存储“任务”的值,如果检索到该值并且该值不是 null 并且不为空,那么只有它会被解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.