جافا سكريبت - كيف أحفظ JSON في ملف نصي محلي


لنفترض أن لدي كائن جافاسكريبت يبدو هكذا:

  var data = {
      name: "cliff",
      age: "34",
      name: "ted",
      age: "42",
      name: "bob",
      age: "12"
    }

var jsonData = JSON.stringify(data);

أنا أحوله إلى سلسلة نصية لتحويله إلى JSON. كيف يمكنني حفظ هذا JSON في ملف نصي محلي حتى أتمكن من فتحه، على سبيل المثال، في Notepad وما إلى ذلك.

الإجابة رقم 1

نود.جي إس:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

المتصفح (واجهة برمجة تطبيقات الويب):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

الإجابة رقم 2

إنها حلي لحفظ البيانات المحلية في ملف نصي.

function export2txt() {
  const originalData = {
    members: [{
        name: "cliff",
        age: "34"
      },
      {
        name: "ted",
        age: "42"
      },
      {
        name: "bob",
        age: "12"
      }
    ]
  };

  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {
    type: "text/plain"
  }));
  a.setAttribute("download", "data.txt");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
<button onclick="export2txt()">Export data to local txt file</button>