Search code examples
javascriptjsonloopsobjectstringify

JSON.stringify not adding commas between contained objects


Although following the excellent information in https://stackoverflow.com/a/47116829/11308019 — especially the "Year 2018 answer" — I am trying to figure out a JSON.stringify problem. Example code follows...

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'})
})

This results in output in .base64imgs.json like the following:

{
  "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"
}

...which obviously isn't valid JSON because there's no comma between the objects within the containing bCache object. (I also tried using arrays only, arrays within an object, objects within an array, etc.; same results each time.) I assume the fault is my own, but my days-long searches for answers in SO and other similar sources haven't shown me what I'm doing wrongly. So, any help and/or correction will be greatly appreciated!


Solution

  • You'll want to use an array instead of an object for bCache. And you should probably write out all at once instead of appending in a loop.

    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))