【问题标题】:Write json object to csv from inside Osmosis function从 Osmosis 函数内部将 json 对象写入 csv
【发布时间】:2019-04-16 13:17:46
【问题描述】:

我正在使用 node.js 工具 Osmosis 将一堆数据提取为 json 对象数组

Osmosis函数的本质似乎是数组只存在于函数的范围内,所以我需要在函数停止运行并处理json文件之前将文件写入函数内部。

这是我提取数据的代码:

    'use strict';
const osmosis = require('osmosis');
const fs = require('fs');
const converter = require('json2csv');
var stringify = require('csv-stringify');

function getOpenGraphMeta() {
  return new Promise((resolve, reject) => {
    let response;

    osmosis 

    .get('https://www.winepeople.com.au/wines/Dry-Red/_/N-1z13zte')
    .find('.product-row.product-bottle')
    .set({
      title: "h2.wine-title",
      headline: "h3.wine-headline",
      text: "p.wine-text"
    })
    .data(res => response = res)
    .error(err => reject(err))
    .done(() => resolve(response));
  });
}

getOpenGraphMeta().then(res => {
  console.log(res);
});


function getHomePageTrending() {
  return new Promise((resolve, reject) => {
  let response = [];   
  let stringToReplaceComas = '!!!!';

    osmosis 

      .get('https://www.winepeople.com.au/wines/Dry-Red/_/N-1z13zte')
      .paginate('#search > div.content.col-xs-12.col-md-9.wine-search-results.search-page > div:nth-child(7) > div > nav > ul > li:nth-child(5) > a', 2)
      .find('.product-row.product-bottle')
      .set({
        title: 'h2.wine-title',
        headline: 'h3.wine-headline',
        text: 'p.wine-text',
        RRP: 'label.product-list-price',
        VPP: 'h2.vpp-price',
        TwelveBottle: 'label.product-price',
        SixBottle: '#js-search-price > div:nth-child(2) > label > b',
      })
      .find('.row.wine-attributes')
      .set({
        Country: '//*[@id="search"]/div[2]/div[6]/div[3]/div/div/div[2]/div[2]/div[1]/text()'
      })
      .data(res => response.push(res))
      .error(err => reject(err))
      .done(() => resolve(response));


  });
}

getHomePageTrending().then(res => {
  console.log(res);
});

我怎样才能将result[] json 对象数组写入磁盘上的 csv?或者甚至只是一个我可以使用 CLT 转换的 json 文件?任何将 json 数组写入磁盘的方法都足够了。

【问题讨论】:

    标签: javascript arrays node.js json json2csv


    【解决方案1】:

    我认为你的工作不需要 csv-stringify

    getOpenGraphMeta().then(res => {
      var jsonstrMinified = JSON.stringify(res); //unformatted
      var jsonstr = JSON.stringify(res, null, 2);  //formatted
      fs.writeFileSync('/path/to/file-on-fisk.json', jsonstr)
    
      var fields = ['title', 'headline', 'text'];
      var parser = new converter.Parser({ fields });
      var csvstr = parser.parse(res);
      fs.writeFileSync('/path/to/file-on-fisk.csv', csvstr));
    })
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多