JSON字符串化偶尔会将分隔符替换为右方括号

46qrfjad  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(133)

我正在运行一个node.js脚本,它在一个目录中进行筛选,提取它找到的任何正则表达式匹配项,然后将它们推送到一个数组中。一旦查询运行完毕,我就将数组字符串化到一个独立的JSON文件中,以便在需要它之前妥善保管。
我遇到了一些零星的错误,JSON文件中的数组格式不正确,当我稍后试图解析它时会导致错误。这是零星的,我无法确定模式,但每次(到目前为止)导致错误的字符都是一个结束方括号--就像下面第二和第三个元素之间的那个:
["first string","second string"]"third string"]
这几乎就像我的array.push()只是在现有数组的末尾添加了另一个元素,并且“忘记”将右方括号改为逗号...
我已经搜索过了,但是找不到会导致这种情况的已知错误的引用。有人以前见过这个吗?
使用环境:节点. js v19.0.0| Ubuntu 22.04.1语言版本|英特尔i7处理器
下面是生成JSON文件的代码:

const fs = require('fs');
const path = require('path');
const devPath = '/home/user/directory';
const activeReminder = [];

function buildArray() {
  let getFiles = fs.readdirSync(devPath);
  getFiles.forEach(file => {
    splitMD(file);
  });
}

function splitMD(file) {
  if (path.extname(file) == ".md" & file != {}) {
    let data = fs.readFileSync(file, 'utf8');
    const line = data.split(/\r?\n/);
     const match = line.find(element => {
        extractions(element, file);
    });
  }
};

function extractions(element, file) {
  if (element.includes("- [ ] reminder: ")) { //the - [ ] is markdown for Obsidian
    const datedReminder = "- [ ] [["+file+"]]" + element.split('- [ ] reminder:')[1]
    activeReminder.push(datedReminder);
    buildReminderJSON();
  } 
}

function buildCcioJSON() {
  const reminderJSON = JSON.stringify(activeReminder);
  fs.writeFile("reminder.json", reminderJSON, 'utf8', function (err) {
    if (err) {
      console.log("Error while writing CCIO JSON:");
      return console.log(err);
    }
  })
}

buildArray();

module.exports = { buildArray };
kkih6yb8

kkih6yb81#

我不知道是什么导致了上述异常,但我创建了一个脚本来纠正它,作为一种解决方案,直到我找到根本原因。

const fs = require('fs')
const path = require('path')
const devPath = '/home/user/directory'

function cleanup() {
    let getFiles = fs.readdirSync(devPath);
    getFiles.forEach(file => {
        splitJSON(file);
    });
  }
  
function splitJSON(file) {
  if (path.extname(file) == ".json" & file != {}) {
    let data = fs.readFileSync(file, 'utf8');
    const line = data.split(/\r?\n/);
     const match = line.find(element => {
        jsonCheck(element, file);
    });
  }
};

function jsonCheck(element, file) {
  if (element.includes("\"]\"")) {
    fs.readFile(file, 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        var result = data.replace(/\"\]\"/g, '","');
        fs.writeFile(file, result, 'utf8', function (err) {
           if (err) return console.log(err);
        });
      });
  }
}
cleanup();
module.exports = { cleanup };

相关问题