0

我开始学习Node JS,我正在尝试将外部JSON文件转换为 CSV 格式。

我要实现的操作如下:在一个内部文件中,我有两个 url,每个 url 都指向一个外部 JSON(api1 和 api2),给定 url http://localhost:3000/?api=api1,你必须下载CSV 格式JSONapi1最大50 行。

这是我到目前为止的代码(我添加了一些我认为是必要的模块):

import { Request, Response } from 'express';

const converter = require("json-2-csv");
const fetch = require("node-fetch");
const fs = require("fs");
const flatten = require('flat');

const conf = require(`../conf/${process.env.NODE_ENV}.json`);
const maxRecords = 50;

class IndexController {
  public async index(req: Request, res: Response) {
    const api =req.query.api; //api1
    const url = conf.API_MOCS[`${api}`].url; //https://mock.com/api1

    const csvWriter = createCsvWriter({
    path: 'path/to/file.csv',
    header: [
        {id: 'index', title: 'Index'},
        {id: 'index_start_at', title: 'Index start'},
        {id: 'integer', title: 'Integer'},
        {id: 'float', title: 'Float'},
        {id: 'name', title: 'Name'}
    ]
});

fetch(url)
  .then(res => res.json())
  .then(json => csvWriter.writeRecords(json.myItems));
  }
}
export const indexController = new IndexController(); 

这是我的内部文件,其中包含 JSON 的 url:

{
  "API_MOCS": {
    "api1": {
      "url": "https://mock.com/api1"
    },
    "api2": {
      "url": "https://mock.com/api2"
    }
  }
}
4

1 回答 1

1

您应该首先从 URL 中“获取”json。有很多库可以帮助您解决这个问题。看看: https ://www.npmjs.com/package/node-fetch 或https://www.npmjs.com/package/axios

然后您可以编写 CSV 文件。我也建议使用图书馆。第一次点击:https ://www.npmjs.com/package/csv-writer

import { Request, Response } from 'express';

const fetch = require("node-fetch");
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

const conf = require(`../conf/${process.env.NODE_ENV}.json`);
const maxRecords = 50;

class IndexController {
  public async index(req: Request, res: Response) {
    const api =req.query.api; //api1
    const url = conf.API_MOCS[`${api}`].url; //https://mock.com/api1
    const csvWriter = createCsvWriter({
      path: 'path/to/file.csv',
      header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
      ]
    });

    fetch(url)
      .then(res => res.json())
      .then(json => csvWriter.writeRecords(json.myItems));
  }
}
export const indexController = new IndexController(); 
于 2021-06-06T10:14:48.353 回答