# JSON 增删改查简单指南 ## 基本说明 所有 JSON 文件保存在 `static` 目录下,使用相对路径即可。 ## 增(Create)- 创建文件 ```javascript await window.electronAPI.runNodejsScript('json-parser', 'create', 'device_list.json', JSON.stringify({devices: []})) ``` ## 查(Read)- 读取文件 ```javascript const result = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json') const jsonData = JSON.parse(result.stdout).data ``` **文件不存在时:** `result.stdout` 为空字符串 `''` ## 改(Update)- 更新文件 ```javascript await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: ['192.168.1.1', '192.168.1.2']})) ``` ## 删(Delete)- 删除元素 删除数组中的元素: ```javascript // 1. 读取 const result = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json') const jsonData = JSON.parse(result.stdout).data // 2. 过滤删除 const filtered = jsonData.devices.filter(ip => ip !== '192.168.1.1') // 3. 更新 await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: filtered})) ``` ## 完整示例 ### 添加设备到数组 ```javascript // 读取 const result = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json') const jsonData = result.stdout === '' ? {devices: []} : JSON.parse(result.stdout).data // 添加 jsonData.devices.push('192.168.1.3') // 更新 await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: jsonData.devices})) ``` ### 删除设备从数组 ```javascript // 读取 const result = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json') const jsonData = JSON.parse(result.stdout).data // 删除 const filtered = jsonData.devices.filter(ip => ip !== '192.168.1.3') // 更新 await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: filtered})) ``` ### 检查文件是否存在 ```javascript const result = await window.electronAPI.runNodejsScript('json-parser', 'check', 'device_list.json') const exists = JSON.parse(result.stdout).exists ```