2015-11-11 25 views
0
编辑本地JSON文件

请回答我,例如Select代码如何使用JavaScript

  1. 我要值添加到阵列的本地文件JSON(插入成员JSON)
  2. 元素也取代了我的元素像typename ...在JSON(在JSON更新部件)
  3. 删除数行,其中id="1"email="[email protected]"(在JSON删除memebr)

JSON文件:report.json

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

例如用于检查登记管理select代码:

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"); 
    } 
} 
+0

你怎么在代码中加入JSON文件?包括什么方法? – murrometz

+1

浏览器中的Javascript没有权限编辑磁盘上的文件。 – Steve

+0

没错。我认为你应该编写php文件来操纵你的json。 (使用json_decode,json_encode函数。)比用你的javascript说话(ajax-post,ajax-get等) – murrometz

回答

0

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

请参阅下面的操作JSON对象。

var amir='{"reports":[' + 
 
    '{"id": "1","type": "admin","name": "amir","email": "[email protected]","password": "123"},' + 
 
    '{"id": "2","type": "member","name": "kevin","email": "[email protected]","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": "[email protected]", 
 
    "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 == [email protected] 
 
    if(obj.reports[c].id == "1" && obj.reports[c].email == "[email protected]") { 
 
    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>