如何将数据记录器结果格式化为 JSON?

How to format data-logger results as JSON?

我有一个数据记录器,它通过附加到文件来记录时间、状态和温度。 (从 cron 作业调用记录器。)

如果我能以 JSON 的形式将数据读入网页脚本就好了,但我没有找到一个好的方法——要么我的记录器更复杂,要么我的reader比较复杂。

我的数据是这样的:

[ timestamp, "status", temperature ]
[ 123456789, "sync",   12345]

我可以很容易地在行尾添加逗号,但无论哪种方式,它的格式都不正确 JSON -- 整个内容都需要括号。

所以要么我的记录器必须检测到一个空数据文件并添加一个前导括号,然后搜索到末尾,备份一个字符,用逗号替换最后一个右括号,然后用一个额外的右括号,或者 reader 必须通过切掉尾随逗号并在周围添加括号来按摩前 JSON。

有更简单的方法吗?

你可以做到

我会用fetch

const str = `[ timestamp, "status", temperature ]
[ 123456789, "sync",   12345]`

const data = str.split(/\r?\n/) // line feed
  .map(line => line
    .replace(/[\[\]]/g,"") // remove square brackets (can be done in the regex below too
    .match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g) // find stuff with or without quotes
    .map(elem => isNaN(elem) ? elem : +elem) // convert numbers back to numbers
  );
console.log(data)

您使用的格式是一种类似的格式,既适用于日志记录又非常适合:请参阅 JSON Lines and ndjson

通过在第一行之后分割您的输入,您将剩下 JSON 行。然后你只需要迭代这些行并解析每一行(如果需要可以选择收集到一个数组中)。

这是一个例子:

const LF = '\n';

function iterateJSONLines (jsonl, cb) {
  for (const line of jsonl.trim().split(LF)) {
    cb(JSON.parse(line));
  }
}

/** handle the first (non-JSON) line in your input */
function separateHeaderFromJSONLines (input) {
  for (let i = 0; i < input.length; i += 1) {
    if (input[i] !== LF) continue;
    return [input.slice(0, i).trim(), input.slice(i + 1)];
  }
}

function main (input) {
  const [headerLine, jsonl] = separateHeaderFromJSONLines(input);
  const arr = [];
  iterateJSONLines(jsonl, arr.push.bind(arr));
  console.log(headerLine);
  console.log(arr);
}

const input = `[ timestamp, "status", temperature ]
[ 123456789, "sync",   12345]
[ 987654321, "anotherStatus",   54321]
`;

main(input);