如何使用JavaScript编辑本地JSON文件

时间:2015-11-11 13:51:21

标签: javascript jquery json

请以示例Select代码

回答我
  1. 我想将值添加到数组本地文件JSON(将成员插入JSON)
  2. 元素也替换为{J}中的typename ...等元素(JSON中的更新成员)
  3. 删除id="1"email="amir@site.com"的数字行(在JSON中删除memebr)
  4. JSON文件:report.json

    var amir='{"reports":[' +
        '{"id": "1","type": "admin","name": "amir","email": "amir@site.com","password": "123"},' +
        '{"id": "2","type": "member","name": "kevin","email": "ad@ad.com","password": "1234"}]}';
    

    示例select代码,用于检查寄存器admin:

    var obj = JSON.parse(amir);
    for(c = 0; c <= obj.reports.length - 1; c++) {
        type = obj.reports[c].type.toString();
        if (type == "admin") {
            active = 1;
        }
    
        if (c == obj.reports.length - 1) {
            if (active == 1)
                alert("Yes");
            else
                alert("No");
        }
    }
    

1 个答案:

答案 0 :(得分:1)

至于将操作JSON的结果保存到磁盘,必须在后端完成,或者您可以打开一个窗口,将该文件作为内容,将MIME类型设置为json,这可能会提示用户将其保存到计算机,具体取决于他们的浏览器设置。请参阅http://www.w3schools.com/jsref/met_doc_open.asp

请参阅下文,了解JSON对象的操作。

var amir='{"reports":[' +
    '{"id": "1","type": "admin","name": "amir","email": "amir@site.com","password": "123"},' +
    '{"id": "2","type": "member","name": "kevin","email": "ad@ad.com","password": "1234"}]}';

var obj = JSON.parse(amir);

document.getElementById("before").innerHTML = JSON.stringify(obj);
console.log("Before", JSON.parse(JSON.stringify(obj))); // objects use pointers, clone it to see the value at this point


// Add a new member into the array (example, using made up values)
obj.reports.push({
  "id": ""+obj.reports.length + 1,
  "type": "member",
  "name": "Joe",
  "email": "asdf@gmail.com",
  "password": "ajdj12oi42"
});

document.getElementById("during").innerHTML = JSON.stringify(obj);
console.log("During", JSON.parse(JSON.stringify(obj))); // objects use pointers, clone it to see the value at this point

// When deleting items, it is often easier to start high, and end low
for(var c = obj.reports.length - 1; c >= 0; c--) {
  // Delete member in JSON where id == 1 and email == amir@site.com
  if(obj.reports[c].id == "1" && obj.reports[c].email == "amir@site.com") {
    obj.reports.splice(c, 1);
  } else {
    // Add values into the objects (example, using random numbers)
    obj.reports[c].newKey = "New Value! " + Math.floor(Math.random() * 100);
  }
}

document.getElementById("after").innerHTML = JSON.stringify(obj);
console.log("After", JSON.parse(JSON.stringify(obj))); // objects use pointers, clone it to see the value at this point
<h1>Before</h1>
<div id="before"></div>

<h1>During</h1>
<div id="during"></div>

<h1>After</h1>
<div id="after"></div>