1.0.3 • Published 6 years ago

json-convert-csv v1.0.3

Weekly downloads
1
License
ISC
Repository
github
Last release
6 years ago

json-convert-csv

npm GitHub stars label

json convert to csv or csv convert to json.

json 数据转换为 csv 表格。

[
  {
    "name": "小白",
    "sex": "男",
    "age": "18",
    "tel": "1383794XXXX"
    "address": "广东省 广州市"
  },
  {
    "name": "小红",
    "sex": "女",
    "age": "14",
    "tel": "1337893XXXX",
    "address": "广东省 广州市"
  }
]
姓名性别年龄电话地址
小白181383794XXXX广东省 广州市
小红141337893XXXX广东省 广州市

Usage

npm install -S json-convert-csv
  • json to csv
const fs = require('fs')
const CSVStream = require('json-convert-csv').CSVStream
const csvSteam = new CSVStream()

const json = fs.createReadStream('path-to-json-file')
const csv = fs.createWriteStream('path-to-csv-file')

json.pipe(csvSteam).pipe(csv)
  • csv to json
const fs = require('fs')
const JSONStream = require('json-convert-csv').JSONStream
const jsonStream = new JSONStream()

const csv = fs.createReadStream('path-to-csv-file')
const JSONFile = fs.createWriteStream('new-path-to-json-file')

csv.pipe(jsonStream).pipe(JSONFile)

Options

new CSVStream(options)

  • options 配置对象
    • header \<string[]> 数据的字段名。['name', 'age', 'tel']
    • headerDisplay \<string[]> 数据的显示名称。['姓名', '年龄', '电话']

Event

new JSONStream(options)

  • options 配置对象
    • fieldNames \<string[]> 字段名数组。
    • lineEnding \<RegExp> 行结束符。默认为/\n/ 。也可设置为 /\r\n/
    • separator \<RegExp> 分隔符。默认为 /[,]/。可设置为 /\t//[ ]/
    • ignoreFirstLine \<boolean> 是否忽略首行。默认 true

Event

  • line 当解析每一行时触发。

parse

参数
名称类型描述
objObject解析的每个对象
indexNumber第几个解析的对象

convert

参数
名称类型描述
convertStrString格式化的字符串。
indexNumber第几个解析的对象

error

参数
名称类型描述
errorError转换过程出现的错误。

line

参数
名称类型描述
objObjectcsv 每一行触析出的对象。

Simple

const convert = new Csv({
  header: ['name', 'age', 'tel'],
  headerDisplay: ['姓名', '年龄', '电话']
})
/*
<<< Input JSON
[
  {
    "name": "小白",
    "age": "18",
    "tel": "1383794XXXX"
  },
  {
    "name": "小红",
    "age": "14",
    "tel": "1337893XXXX"
  }
]
>>> Output CSV
*/
姓名年龄电话
小白181383794XXXX
小红141337893XXXX
1.0.3

6 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago