How to use json2csv - 10 common examples

To help you get started, we’ve selected a few json2csv examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / json2csv / json2csv-tests.ts View on Github external
const input = createReadStream('/path/to/input', { encoding: 'utf8' });
const output = createWriteStream('path/to/output', { encoding: 'utf8' });

asyncParser.fromInput(input).promise()
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

asyncParser.fromInput(input).toOutput(output);

// Test convenience method "parseAsync" with object input
parseAsync(data, opts)
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

// Test convenience method "parseAsync" with stream input
parseAsync(input, opts)
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

/********************
 * Internal Methods *
 ********************/
class ParserExt extends Parser {
    constructor() {
        super();
        // Parser methods
        obj = this.preprocessData({});
        obj = this.preprocessData({ str: '', num: 1, obj: {} });
        obj = this.preprocessData([]);
        s = this.processData([]);

        // JSON2CSVBase methods
github DefinitelyTyped / DefinitelyTyped / types / json2csv / json2csv-tests.ts View on Github external
.on('error', err => console.log(err));

asyncParser.input.push(data); // This data might come from an HTTP request, etc.
asyncParser.input.push(null); // Sending `null` to a stream signal that no more data is expected and ends it.

const input = createReadStream('/path/to/input', { encoding: 'utf8' });
const output = createWriteStream('path/to/output', { encoding: 'utf8' });

asyncParser.fromInput(input).promise()
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

asyncParser.fromInput(input).toOutput(output);

// Test convenience method "parseAsync" with object input
parseAsync(data, opts)
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

// Test convenience method "parseAsync" with stream input
parseAsync(input, opts)
    .then(csv => console.log(csv))
    .catch(err => console.error(err));

/********************
 * Internal Methods *
 ********************/
class ParserExt extends Parser {
    constructor() {
        super();
        // Parser methods
        obj = this.preprocessData({});
github DefinitelyTyped / DefinitelyTyped / types / json2csv / json2csv-tests.ts View on Github external
} catch (err) {
    console.error(err);
}

// Test convenience method "parse"
try {
    const csv = parse(data, opts);
    console.log(csv);
} catch (err) {
    console.error(err);
}

// Test for Asynchronous Parser
const transformOpts = { highWaterMark: 8192 };

const asyncParser = new AsyncParser(opts, transformOpts);

let csv = '';
asyncParser.processor
    .on('data', chunk => (csv += chunk.toString()))
    .on('end', () => console.log(csv))
    .on('error', err => console.error(err));

// Test for transform events
asyncParser.transform
    .on('header', header => console.log(header))
    .on('line', line => console.log(line))
    .on('error', err => console.log(err));

asyncParser.input.push(data); // This data might come from an HTTP request, etc.
asyncParser.input.push(null); // Sending `null` to a stream signal that no more data is expected and ends it.
github DefinitelyTyped / DefinitelyTyped / types / json2csv / json2csv-tests.ts View on Github external
num?: number;
    obj?: object;
}

/**************
 * Public API *
 **************/
parse({});
parse([]);
parse({}, {});

new Parser();
const parser: Parser = new Parser({});
s = parser.parse({ str: '', num: 1, obj: {} });
parser.parse([]);
const transform: Transform = new Transform({ quote: '' });
const nodeTransform: NodeTransform = transform;

// Tests using examples from Readme
interface Car {
    car: string;
    price: number;
}

const opts: json2csv.Options = {
    fields: [
        // Supports pathname -> pathvalue
        'simplepath', // equivalent to {value:'simplepath'}
        'path.to.value', // also equivalent to {value:'path.to.value'}

        // Supports label -> simple path
        {
github alexieyizhe / intern.plus / server / migration / convertToCSV.js View on Github external
file: reviewJsonFile,
  },
};

// review, company, or job
const typeArg = process.argv[2];

if (!["-c", "-j", "-r"].includes(typeArg)) {
  console.log(
    "One of '-c', '-j', or '-r' must be specified to indicate which file type to convert!"
  );
  process.exit(1);
}

const dictEntry = dict[typeArg];
const json2csvParser = new Parser({ fields: dictEntry.fields });
const jsonInput = dictEntry.file;

console.log("Parsing...");
const csvOutput = json2csvParser.parse(jsonInput);

console.log(`Outputting to ./migration/${dictEntry.key}.csv`);
fs.writeFileSync(`./migration/${dictEntry.key}.csv`, csvOutput, () => {});

console.log("Done migration!");
github nteract / semiotic / src / components / DownloadButton.tsx View on Github external
import * as React from "react"
import { Parser } from "json2csv"

const json2csv = new Parser()

export const downloadCSV = (csvName: string, data: any) => {
  const CSV = json2csv.parse(data)
  const blob = new Blob([CSV], { type: "text/csv" })

  const dlink = document.createElement("a")
  dlink.download = csvName ? `${csvName.replace(/ /g, "_")}.csv` : "vis.csv"
  dlink.href = window.URL.createObjectURL(blob)
  dlink.onclick = () => {
    // revokeObjectURL needs a delay to work properly
    const revokeFn = () => {
      window.URL.revokeObjectURL(dlink.href)
    }
    setTimeout(revokeFn, 1500)
  }
github webiny / webiny-js / packages / api-forms / src / plugins / graphql / formSubmissionResolvers / exportFormSubmissions.js View on Github external
// Build rows.
    for (let i = 0; i < submissions.length; i++) {
        let submissionData = submissions[i].data;
        const row = {};
        Object.keys(fields).map(fieldId => {
            if (fieldId in submissionData) {
                row[fields[fieldId]] = submissionData[fieldId];
            } else {
                row[fields[fieldId]] = "N/A";
            }
        });
        rows.push(row);
    }

    // Save CSV file and return its URL to the client.
    const csv = await parseAsync(rows, { fields: Object.values(fields) });
    const buffer = Buffer.from(csv);
    const result = await uploadFile({
        context,
        buffer,
        file: {
            size: buffer.length,
            name: "form_submissions_export.csv",
            type: "text/csv"
        }
    });
    return new Response(result);
};
github IBM / report-toolkit / packages / transformers / src / csv.js View on Github external
export const transform = (parserOpts = {}) => observable => {
  // XXX: the parser wants to add a newline to everything we push to it for
  // some reason. likely "user error"
  const parser = new AsyncParser(
    {...parserOpts, eol: '', flatten: true},
    {
      objectMode: true
    }
  );
  return observable.pipe(
    finalize(() => {
      parser.input.push(null);
    }),
    tap(row => {
      parser.input.push(row);
    }),
    concatMapTo(fromEvent(parser.processor, 'data')),
    takeUntil(fromEvent(parser.processor, 'end')),
    filter(Boolean),
    map(_.pipe(_.trim, stripAnsi))
github amerker / google-keep-converter / test / saver.spec.js View on Github external
test('JSON and CSV files are written and match with input data', (t) => {
  writeFile(notesStub, true, 'bar');

  const jsonFileContent = fs.readFileSync('bar.json', 'utf-8');
  t.deepEqual(JSON.parse(jsonFileContent), notesStub);

  t.notThrows(() => {
    fs.lstatSync('bar.csv');
  });

  const csvFileContent = fs.readFileSync('bar.csv', 'utf-8');
  t.is(csvFileContent, json2csv({ data: notesStub }));
});
github ali1k / ld-r / components / dataset / Facet.js View on Github external
handleExport(){
        let values =[];
        this.filteredInstances.forEach((instance)=>{
            values.push({item: instance.value, resourceNo: instance.total})
        })
        let csv = json2csv.parse(values, {fields: ['item', 'resourceNo']});
        //console.log(csv);
        let uriContent = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
        window.open(uriContent, 'dataF.csv');
    }
    checkItem(status, value) {

json2csv

Convert JSON to CSV

MIT
Latest version published 2 years ago

Package Health Score

76 / 100
Full package analysis