如何用Express将对象数组正确写入JSON文件?
问题:Express后端写入JSON文件格式不符预期
我用Express后端从React客户端接收对象数组格式的数据,想要写入JSON文件,但生成的结果和预期不符。
后端代码
export const addStatements = async (req,res) => { console.log(req.body) // form fields fs.writeFile('./categories.json', JSON.stringify(req.body), err => { if (err) throw err; console.log("Done writing!") }) }
接收的数据
后端收到的req.body结构如下:
{ categoryFilename: '[{"description":"GOOGLE","category":"MISC"},{"description":"AMZN","category":"MERCHANDISE"},{"description":"MCDONALD","category":"DINNING"},{"description":"SAFEWAY","category":"GROCERIES"},{"description":"WISH","category":"MERCHANDISE"},{"description":"99 RANCH","category":"GROCERIES"},{"description":"PARKMOBILE","category":"COLLEGE FEE"},{"description":"CITY OF SAN RAMON","category":"TENNIS"},{"description":"FILA","category":"APPAREL"},{"description":"COMCAST","category":"TELECOM"},{"description":"PEETS","category":"COFFEE"}]' }
当前生成的JSON文件内容
{"categoryFilename":"[{\"description\":\"GOOGLE\",\"category\":\"MISC\"},{\"description\":\"AMZN\",\"category\":\"MERCHANDISE\"},{\"description\":\"MCDONALD\",\"category\":\"DINNING\"},{\"description\":\"SAFEWAY\",\"category\":\"GROCERIES\"},{\"description\":\"WISH\",\"category\":\"MERCHANDISE\"},{\"description\":\"99 RANCH\",\"category\":\"GROCERIES\"},{\"description\":\"PARKMOBILE\",\"category\":\"COLLEGE FEE\"},{\"description\":\"CITY OF SAN RAMON\",\"category\":\"TENNIS\"},{\"description\":\"FILA\",\"category\":\"APPAREL\"},{\"description\":\"COMCAST\",\"category\":\"TELECOM\"},{\"description\":\"PEETS\",\"category\":\"COFFEE\"}]"}
期望的JSON文件格式
[{"description":"GOOGLE","category": "MISC"},{"description":"AMZN","category":"MERCHANDISE"},{"description":"MCDONALD","category":"DINNING"},{"description":"SAFEWAY","category":"GROCERIES"},{"description":"WISH","category":"MERCHANDISE"},{"description":"99 RANCH","category":"GROCERIES"},{"description":"PARKMOBILE","category":"COLLEGE FEE"},{"description":"CITY OF SAN RAMON","category":"TENNIS"},{"description":"FILA","category":"APPAREL"},{"description":"COMCAST","category":"TELECOM"},{"description":"PEETS","category":"COFFEE"}]
解决方案
问题核心是:你接收的req.body.categoryFilename是已经被JSON序列化的字符串,不是直接的数组。所以需要先把这个字符串解析成JS数组,再写入文件。
修改后的代码:
export const addStatements = async (req,res) => { console.log(req.body) try { // 解析categoryFilename对应的JSON字符串为数组 const dataArray = JSON.parse(req.body.categoryFilename); // 写入文件,第二个参数加null,2是为了生成格式化的JSON,可选 fs.writeFile('./categories.json', JSON.stringify(dataArray, null, 2), err => { if (err) { console.error('写入文件出错:', err); return res.status(500).send('写入文件失败'); } console.log("Done writing!") res.status(200).send('写入成功'); }) } catch (parseErr) { console.error('解析JSON字符串出错:', parseErr); res.status(400).send('数据格式错误'); } }
额外建议
如果可以调整客户端代码,建议直接发送数组本身,而不是把数组转成字符串后放在categoryFilename字段里。比如客户端发送POST请求时,直接传数组:
// 客户端示例代码 const data = [{"description":"GOOGLE","category":"MISC"}, ...]; fetch('/api/addStatements', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), });
这样后端可以直接用req.body写入文件,代码更简洁:
export const addStatements = async (req,res) => { fs.writeFile('./categories.json', JSON.stringify(req.body, null, 2), err => { if (err) { console.error(err); return res.status(500).send('写入失败'); } console.log("Done writing!") res.status(200).send('写入成功'); }) }
内容的提问来源于stack exchange,提问作者user7087799
相关产品推荐
相关产品推荐

