【问题标题】:JSON.stringify not adding commas between contained objectsJSON.stringify 不在包含的对象之间添加逗号
【发布时间】:2020-09-25 03:55:09
【问题描述】:

尽管遵循https://stackoverflow.com/a/47116829/11308019 中的优秀信息——尤其是“2018 年答案”——我试图找出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 和其他类似来源中寻找答案的时间长达数天'没有告诉我我做错了什么。因此,任何帮助和/或更正将不胜感激!

【问题讨论】:

  • 不应该bCache 是一个数组而不是一个对象?所以let bCache = [];bCache = [...bCache, bAdd];
  • @HereticMonkey 确实尝试了上一段中提到的所有组合。没有喜悦。 :-/
  • 除了数组而不是对象之外,您的部分问题是使用 ...bAdd 而不仅仅是 bAdd — Heretic Monkey 显示了它但没有提及它......你想添加 object,但使用...bAdd,您首先使用扩展运算符扩展 bAdd,然后将扩展添加到bCache。
  • @HereticMonkey --- 从下面其他人所说的来看,看起来我一开始就应该听你的。谢谢。

标签: javascript json loops object stringify


【解决方案1】:

您将希望对 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))

【讨论】:

  • 谢谢。看起来这样就可以了。标记为答案。
【解决方案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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2016-07-05
    • 1970-01-01
    相关资源
    最近更新 更多