如何将json转换为NDJSON以便插入BQ?

问题描述

我正在使用nodejs抓取一些数据并将其加载到bigquery中。我的问题是BQ需要NDJSON。 JSON到NDJSON,没问题吧?好吧,我似乎找不到一个好的解决方案。

现在,我的方法是将数据写入临时目录中的磁盘,然后使用exec调用jq转换为NDJSON。然后,我读取文件并返回NDJSON。请参见下面的代码示例中的函数。有没有更好的方法可以做到这一点,而不涉及将数据写入磁盘?我还注意到,函数第一次运行时会失败(读取新文件中的数据时出错),但此后工作正常。我到处看了看似可以使用的各种工具,但似乎没有一个将json转换为NDJSON的直接方法

async function getJSON(data) {
    try {
      // BigQuery only accepts NDJSON
      const workingDir = path.join(tmpdir(),'thumbs');
      const tmpFilePath = path.join(workingDir,'temp.json'); 
      const formattedFilePath = path.join(workingDir,'formatted.json'); 
  
      await fs.ensureDir(workingDir);
      await fs.writeJSON(tmpFilePath,data);
  
      exec(`cat ${tmpFilePath} | jq -c '.[]' > ${formattedFilePath}`,(err,stdout,stderr) => {
        if (err) {
            // node Couldn't execute the command
            logger.error(`stderr: ${stderr}`);
            return;
        }
      });
  
      const parsedResults = fs.readFileSync(formattedFilePath);
      return parsedResults;
    } catch (error) {
      logger.error(error);
    }
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)