JSON.stringify 不在包含的对象之间添加逗号

JSON.stringify not adding commas between contained objects

尽管遵循了 中的优秀信息——尤其是 "Year 2018 answer"——我正在尝试找出一个 JSON.stringify 问题。示例代码如下...

const globAll = require('glob-all')
const fs = require('fs')
const cacheFile = '.base64imgs.json'

// clear cacheFile...
fs.writeFileSync(cacheFile,'')
let bCache = {}

files = globAll.sync([
  'src/images/*.jpg',
  'src/images/*.png',
])

files.forEach(file => {
  var bRes = `data for ${file} would go here`
  var bAdd = {file, bRes}
  bCache =  {...bCache, ...bAdd}
  fs.writeFileSync(cacheFile, JSON.stringify(bCache, null, 2), {flag: 'a'})
})

这会导致 .base64imgs.json 中的输出如下所示:

{
  "file": "src/images/1984-07-11_01_retouched_1280x720.jpg",
  "bRes": "data for src/images/1984-07-11_01_retouched_1280x720.jpg would go here"
}{
  "file": "src/images/2020-01-31--curmudgeonishish-2019_1280x726.jpg",
  "bRes": "data for src/images/2020-01-31--curmudgeonishish-2019_1280x726.jpg would go here"
}{
  "file": "src/images/alarm-clock-4711181_1280x853.jpg",
  "bRes": "data for src/images/alarm-clock-4711181_1280x853.jpg would go here"
}{
  "file": "src/images/almond-21502_1280x853.jpg",
  "bRes": "data for src/images/almond-21502_1280x853.jpg would go here"
}

...这显然是无效的 JSON 因为包含 bCache 对象中的对象之间没有逗号。 (我也试过只使用数组,对象中的数组,数组中的对象等;每次都得到相同的结果。)我认为错误是我自己的,但我在 SO 和其他类似来源中寻找答案的天数一直没有'告诉我我做错了什么。所以,任何帮助 and/or 更正将不胜感激!

您需要为 bCache 使用数组而不是对象。而且您应该一次写出所有内容,而不是循环追加。

let bCache = []
let files = ['file 1','file 2','file 3']

files.forEach(file => {
  var bRes = `data for ${file} would go here`
  var bAdd = {file, bRes}
  bCache = [...bCache, bAdd]
})
console.log(JSON.stringify(bCache, null, 2))

不要在循环内写JSON。将所有数据创建一个数组,在循环结束时写入一次。

const globAll = require('glob-all')
const fs = require('fs')
const cacheFile = '.base64imgs.json'

files = globAll.sync([
  'src/images/*.jpg',
  'src/images/*.png',
])

bCache = files.map(file => {
  var bRes = `data for ${file} would go here`
  return {file, bRes}
});

fs.writeFileSync(cacheFile, JSON.stringify(bCache, null, 2));