如何将json formate保存到本地存储后保存?

时间:2017-04-27 09:40:17

标签: javascript json

function receivedText(e) {
  lines = e.target.result;
  obj = JSON.parse(lines);
  split();
}
function split() {
    console.log(obj);
    for (var i in obj) {
        console.log(i);     
        if(i=="tagClassifications"){
            console.log("tagClassifications IS MATCHED");
            var c1=obj[i];
            var ob2=JSON.stringify(c1);
            console.log(ob2);
            var obj1="{ \"tagClassifications\": "+ob2+" }";
            console.log(obj1);
            saveText(c1, "tagClassifications"+".json" );    
        }
        if(i=="tagAssociations"){
            console.log("tagAssociations IS MATCHED");
            var c1=obj[i];
            console.log(c1);
            for(var j in c1){
                console.log(c1[j]);
                console.log("Length="+c1.length+"j:"+j);
                var ob2=JSON.stringify(c1[j]);
                var obj1="{ tagAssociations"+": ["+ob2+"]}";
                console.log(obj1);
                saveText(obj1, "tagAssociations"+j+".json" );                                   
            }               
        }
    }       
}
function saveText(text, filename){
    var a = document.createElement('a');
    a.setAttribute('href', 'data:application/json;charset=utf-8,'+encodeURIComponent(text));
    a.setAttribute('download', filename);
    a.click();
}

在上面的javascript中我将json对象转换为文本文件并将其保存为json格式。但保存的json文件扩展名为.json,但格式为纯文本。请告诉我如何保存json格式。

1 个答案:

答案 0 :(得分:0)

在评论中,澄清了您正在寻找通过缩进将JSON字符串拆分为多行的方法。

为此你可以使用JSON.stringify的第三个参数。此外,最好将此转换延迟到JSON字符串,直到构造完整个对象为止,因此包括 tagClassigifications tagAssociations 键名。

处理 tagClassigifications 的部分如下所示:

var c1 = obj[i];
var obj2 = { tagClassifications: c1 }; // first build the object
var json = JSON.stringify(obj2, null, 2); // only then stringify
console.log(json);

你会为 tagAssociations 做类似的事情。

相关问题