简体   繁体   中英

How to add or push data to local JSON file using javascript only

I'm reading JSON file and delete the element after exact match. I want to push the remaining data to the JSON file after delete.

readJsonFile("./objects.json", function(jsonData){
  let parsedData = jsonData; // Parsed JSON data
    for (let i=0; i <= parsedData.data.length - 1; i++) {
      if (parsedData.data[i].id == did) {
         console.log('match record-->',parsedData.data[i].id);
         console.log('deleted record-->',did);
         if (delete parsedData.data.splice(i,1)) {
              // here I want to push the data to JSON file after delete
         }
      }
    }
});

Below is the the readJsonFile function

function readJsonFile(file, callback) {
  let jsonData;
  $.getJSON(file)
  .done(function (data) {
    jsonData = data;
    callback(jsonData);
  });
}

Assuming from this using jQuery, this is in the browser.

The browser can't write to the local file system, so you can't directly edit the file.

You could do something like (untested):

const blob = new Blob([JSON.stringify(parsedData)], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'), {download: 'new.json', href: url});
document.body.appendChild(a);
a.click();

to try and force the page to download the new JSON data.

You could store your JSON file local into localStorage for example. You could use this as following:

To store the array (or object):

localStorage.setItem('data', JSON.stringify(array));

To get the array (or object):

var data = JSON.parse(localStorage.getItem('data') || '[]');

Example

var array =
[
    {
        user: {icon: 'f007'},
        home: {icon: 'f015'},
        folder: {icon: 'f07c'}
    }
];

localStorage.setItem('data', JSON.stringify(array));

function readJsonFile(jsonData, callback)
{
    callback(jsonData);
}

var data = JSON.parse(localStorage.getItem('data') || '[]');

readJsonFile(data, function(data)
{
    console.log(data[0].home.icon); // f015
});

If you have an Uncaught SecurityError then read this site .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM