【发布时间】: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