nodeJs修改json文件中的数据
// 注意,在内部读取文件不能访问 json 文件中的属性,不知道为什么,所以在外部读取文件 const detailArr = require('./data/Details_shoplist_info.json'); app.get('/api/modify_details_info',function (req, res) { // 获取 GET 的请求数据 let item = req.query.item; let param = req.query.param; // 操作对象中的属性 detailArr.message[0][item] = param; // 将文件转为 JSON 字符串 let result = JSON.stringify(detailArr); // 将修改后的对象存回 json 文件中 fs.writeFile("./data/Details_shoplist_info.json",result,"utf8",function (err, data1) { if(err){ console.error(err); } else{ console.log("点赞成功!"); res.send(JSON.stringify(data1)); } }) })
node.js批量处理json文件
处理一批数据(一堆json文件),要求如下:
// 原始数据 { ?? ?v: { ?? ??? ?code: xxx, // 此属性可能存在,可能不存在 ?? ??? ?a: xxx, ?? ??? ?b: xxx, ?? ??? ?c: xxx ?? ?} } // 处理后 { ?? ?code: 文件名 ?? ?a: xxx, ?? ?b: xxx, ?? ?c: xxx }
心理活动
如果一条一条改的话,额。。。好无聊,刚刚可以批处理修改文件名,那能不能通过 node 批量处理一下内容呢?百度一下,node 读文件、写文件,OK,开干
实操
var fs = require('fs');//引用文件系统模块 const path = require('path'); function readFileList(path, filesList) { ? ? var files = fs.readdirSync(path); ? ? files.forEach(function (itm, index) { ? ? ? ? var stat = fs.statSync(path + itm); ? ? ? ? if (stat.isDirectory()) { ? ? ? ? ? ? //递归读取文件 ? ? ? ? ? ? readFileList(path + itm + "/", filesList) ? ? ? ? } else { ? ? ? ? ? ? var obj = {};//定义一个对象存放文件的路径和名字 ? ? ? ? ? ? obj.path = path;//路径 ? ? ? ? ? ? obj.filename = itm//名字 ? ? ? ? ? ? filesList.push(obj); ? ? ? ? } ? ? }) } var getFiles = { ? ? //获取文件夹下的所有文件 ? ? getFileList: function (path) { ? ? ? ? var filesList = []; ? ? ? ? readFileList(path, filesList); ? ? ? ? return filesList; ? ? }, }; //获取文件夹下的所有文件 let fileLists = getFiles.getFileList('./'); fileLists.forEach(item => { ? ? if (path.extname(item.filename) === '.json') { ? ? ? ? fs.readFile(path.join(__dirname, `./${item.filename}`), 'utf8', function (err, data) { ? ? ? ? ? ? if (err) throw err; ? ? ? ? ? ? let list = JSON.parse(data); ? ? ? ? ? ? const keys = Object.keys(list); ? ? ? ? ? ? const filename = item.filename.replace(path.extname(item.filename), ''); ? ? ? ? ? ? let target = { code: filename }; ? ? ? ? ? ? let newData = Object.assign(target, list[keys]); ? ? ? ? ? ? newData.code = filename; ? ? ? ? ? ? // 将内容写入文件 ? ? ? ? ? ? fs.writeFile(`./${item.filename}`, JSON.stringify(newData), 'utf8', (err) => { ? ? ? ? ? ? ? ? if (err) throw err; ? ? ? ? ? ? ? ? console.log('success done'); ? ? ? ? ? ? }); ? ? ? ? }) ? ? } })
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于在nodeJs中如何修改json文件中的数据的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did119870