-2

I first get a JSON array using this JavaScript code:

$.getJSON("myJSONfile.json")
    .done(function(data) {
      myData = data;
    }); 

myData is a global variable.

I then add information to myData. How do then update the myJSONfile.json to contain the new data.

Sorry if that was confusing. Josh

dlaliberte
  • 3,250
  • 2
  • 25
  • 22

3 Answers3

2

You can not write to any file using JavaScript alone. Just cookies or local (or session) storage. You can write JSON into local storage and just use JSON.stringify to serialize a JavaScript object.

localStorage.setItem('myData', JSON.stringify(myData));

And to retrieve the object

var myData = JSON.parse(localStorage.getItem('myData'));

If you really want to write something in the file, you need use the server script like php or asp. Send myData to the php, and php will write what you want.

<?php
$myData = $_GET['myData']

$fp = fopen('myJSONfile.json', 'w');
fwrite($fp, json_encode($myData));
fclose($fp);

?> 
Hongbin Wang
  • 1,186
  • 2
  • 14
  • 34
0

// step 1: send data to the server

$.post("handler.php", {data: myData}).done(function(){
    //do something after upload
})

// step 2: write it to the file using PHP

<?php
$json = $_POST['data'];

/* sanity check */
if (json_decode($json) != null)
{
   $file = fopen('myData.json','w+');
   fwrite($file, $json);
   fclose($file);
}
else
{
  // user has posted invalid JSON, handle the error 
}
?>
ArtemSky
  • 1,173
  • 11
  • 20
-1

The data received should now be in the myData variable. I would recommend putting a debugger; statement in your code so that you can have a look at the data you have received.

$.getJSON("myJSONfile.json")
.done(function(data) {
  myData = data;
  debugger;
}); 

If you open up developer tools in chrome and select sources, the next time you run your code, it will pause on the debugger; and allow you to enter myData into the console and peer into the object.

Once you know this you should be able to set myData.aProperty = 'newValue'

dmoo
  • 1,509
  • 13
  • 16