如何真正添加数据到JSON文件

时间:2015-12-28 15:37:56

标签: javascript jquery json ajax

一切正常,添加了对象newCar,但它没有被添加到外部" example.json"文件,即文件没有新对象(car:" bmw",model:" x5")。是否可以将这种数据添加到JSON文件中?

JSON文件(" example.json"):



[
  {
    "car":"citroen",
    "model":"saxo"
  },
  {
    "car":"peugeot",
    "model":"106"
  }
]




JavaScript的:



$.getJSON("example.json", function(data) {
	for(var i=0; i<data.length; i++)
		console.log(data[i].car); 
    //citroen
    //peugeot

	var newCar = {car:"bmw",model:"x5"}

	data.push(newCar);
			
	for(var i=0; i<data.length; i++)
		console.log(data[i].car);
    //citroen
    //peugeot
    //bmw
});
&#13;
&#13;
&#13;

添加新对象后,我希望JSON文件(&#34; example.json&#34;)如下所示:

&#13;
&#13;
[
  {
    "car":"citroen",
    "model":"saxo"
  },
  {
    "car","peugeot",
    "model":"106"
  },
  {
    "car","bmw",
    "model":"x5"
  }
]
&#13;
&#13;
&#13;

0 个答案:

没有答案