在 Javascript 中更新 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19873094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:06:41  来源:igfitidea点击:

Updating JSON file in Javascript

javascriptjsonstringparsing

提问by andor kesselman

On a program that I am working on, I send a literal variable to local strorage with JSON.stringify. The plan is I want to constantly update the local storage and add onto the existing local storage. I'm getting problems with the parsing aspect of the JSON file. My code for adding to storage is this:

在我正在处理的程序中,我使用 JSON.stringify 将文字变量发送到本地存储。计划是我想不断更新本地存储并添加到现有的本地存储上。我在解析 JSON 文件方面遇到问题。我添加到存储的代码是这样的:

function addtoStorage(key, data) {
    if (typeof(Storage) !== "undefined") {
    if (localStorage[key]) {
        console.log("Local Storage stuff" + localStorage[key]);
        var olddata = JSON.parse(localStorage[key]);
        var dataJSON = JSON.stringify(olddata + data);
        localStorage[key] = localStorage[key] + dataJSON;
    }
    else {
        var dataJSON = JSON.stringify(data);
        localStorage[key] = dataJSON;
    }
}
else {
    console.log("You don't have storage capabilities. Sorry. Next time improve your browser.");
}

} ;

};

And my output is this on console.log is:

我在 console.log 上的输出是:

Local Storage stuff{"asdf":"","tes":6,"type":"asdf","ast":1,"sd":"","ew":"","asdf":{"te":0,"wer":0},"asf":"","te":"","context":{"asdf":1,"total_hits":0,"asdf":1,"tew":0,"asdf":"","tes":"","date":"asfd-asdf-","asdf":0},"asdf":""}"[object Object][object Object]" main.js:487

Uncaught SyntaxError: Unexpected string

未捕获的语法错误:意外的字符串

I'm fairly sure I understand what the problem is. I just can't seem to figure out how to fix it. It is obviously closing out the JSON object too soon, any recommendations???

我很确定我明白问题是什么。我似乎无法弄清楚如何解决它。显然过早关闭了 JSON 对象,有什么建议吗???

回答by Alex W

I don't think you should be doing olddata + datasince stringifyis for parsing JavaScript objects to JSON and you can't just add two objects together.

我认为您不应该这样做,olddata + data因为stringify用于将 JavaScript 对象解析为 JSON,并且您不能将两个对象添加到一起。

You should try implementing an object merge function, like the one jQuery uses:

您应该尝试实现一个对象合并函数,就像 jQuery 使用的那样:

function merge( first, second ) {
                var len = +second.length,
                        j = 0,
                        i = first.length;

                for ( ; j < len; j++ ) {
                        first[ i++ ] = second[ j ];
                }

                first.length = i;

                return first;
        }

then just do

然后就做

var newdata = merge(olddata, data);
var dataJSON = JSON.stringify(newdata);

https://github.com/jquery/jquery/blob/master/src/core.js#L390

https://github.com/jquery/jquery/blob/master/src/core.js#L390

回答by FabianCook

Uncaught SyntaxError: Unexpected stringis coming from JSON.parse, this is because it is no longer valid JSON (http://json.org/)

Uncaught SyntaxError: Unexpected string来自JSON.parse,这是因为它不再是有效的 JSON ( http://json.org/)

What you are doing is adding an object to an object, which turns out to be a string

你正在做的是向一个对象添加一个对象,结果是一个字符串

enter image description here

在此处输入图片说明

Then when you go to stringify it, the entire thing will be taken is just a string the first time and the second time. So it will go through fine, then the third time when it tries to parse it, the function will fail because you have added a JSON object with a string.

然后当你去字符串化它时,整个事情将被第一次和第二次拿走只是一个字符串。所以它会顺利通过,然后当它第三次尝试解析它时,该函数将失败,因为您添加了一个带有字符串的 JSON 对象。

If you are only storing JSON objects you can use jQuery's extend function (http://api.jquery.com/jQuery.extend/)

如果您只存储 JSON 对象,您可以使用 jQuery 的扩展功能(http://api.jquery.com/jQuery.extend/

Or if you are storing more then just objects change it all to an array

或者,如果您要存储更多,则只是对象将其全部更改为数组

This should cover everything

这应该涵盖一切

function addtoStorage(key, data) {
    if (typeof(Storage) !== "undefined") {
        if (localStorage.getItem(key)) {
            console.log("Local Storage stuff" + localStorage.getItem(key));
            var olddata = JSON.parse(localStorage.getItem(key));
            var newdata = null;
            if(olddata instanceof Array){
                olddata.push(data);
                newdata = olddata;
            }else if(data instanceof Array || !(data instanceof Object) || !(olddata instanceof Object)){
                newdata = [olddata, data];
            }else if(data instanceof Object && olddata instanceof Object){
                newdata = $.extend(olddata, data);
            }
            var dataJSON = JSON.stringify(newdata);
            localStorage.setItem(key, dataJSON);
        }
        else {
            var dataJSON = JSON.stringify(data);
            localStorage.setItem(key, dataJSON);
        }
    }
    else {
        console.log("You don't have storage capabilities. Sorry. Next time improve your browser.");
    }
}