|
| 1 | +// lib/io/json.ts |
| 2 | + |
| 3 | +export const saveJsonToFile = (filename: string, JsonData: any): void => { |
| 4 | +try { |
| 5 | +const blob = new Blob([JSON.stringify(JsonData, null, 2)], { |
| 6 | +type: 'application/json' |
| 7 | +}); |
| 8 | +const url = URL.createObjectURL(blob); |
| 9 | +const a = document.createElement('a'); |
| 10 | +a.href = url; |
| 11 | +a.download = filename; |
| 12 | +document.body.appendChild(a); |
| 13 | +a.click(); |
| 14 | +document.body.removeChild(a); |
| 15 | +URL.revokeObjectURL(url); |
| 16 | +alert('File saving!'); |
| 17 | +} catch (error) { |
| 18 | +console.error('Error saving JSON:', error); |
| 19 | +alert('Failed to save file.'); |
| 20 | +} |
| 21 | +}; |
| 22 | + |
| 23 | +export const loadJsonFromFile = (): Promise<any> => { |
| 24 | +return new Promise((resolve, reject) => { |
| 25 | +const fileInput = document.createElement('input'); |
| 26 | +fileInput.type = 'file'; |
| 27 | +fileInput.accept = '.json'; |
| 28 | +fileInput.style.display = 'none'; |
| 29 | +document.body.appendChild(fileInput); |
| 30 | + |
| 31 | +fileInput.addEventListener('change', async (event) => { |
| 32 | +try { |
| 33 | +const file = (event.target as HTMLInputElement).files?.[0]; |
| 34 | +if (!file) { |
| 35 | +reject(new Error('No file selected.')); |
| 36 | +return; |
| 37 | +} |
| 38 | +const reader = new FileReader(); |
| 39 | +reader.onload = async (e) => { |
| 40 | +try { |
| 41 | +const contents = e.target?.result; |
| 42 | +if (typeof contents === 'string') { |
| 43 | +const parsedData = JSON.parse(contents); |
| 44 | +resolve(parsedData); |
| 45 | +} else { |
| 46 | +reject(new Error('File contents are not a string.')); |
| 47 | +} |
| 48 | +} catch (error) { |
| 49 | +reject(new Error('Error parsing JSON.' + error)); |
| 50 | +} |
| 51 | +}; |
| 52 | +reader.onerror = () => reject(new Error('Error reading file.')); |
| 53 | +reader.readAsText(file); |
| 54 | +} catch (error) { |
| 55 | +console.error('Error during file handling:', error); |
| 56 | +reject(new Error('Error loading JSON:' + error)); |
| 57 | +} finally { |
| 58 | +document.body.removeChild(fileInput); |
| 59 | +} |
| 60 | +}); |
| 61 | +fileInput.click(); |
| 62 | +}); |
| 63 | +}; |
0 commit comments