cmds

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2020 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const Service = "tabcot"

Service service name

Variables

View Source
var Execute = xcmd.Init(func(cmd *xcmd.Command) {
	xenv.Cfg.Service = Service
	xenv.Cfg.Version = version.Version

	var expr string = ""

	cmd.PersistentFlags().StringVarP(&expr, "expr", "k", expr, "json path")
	cmd.Example = "tabcot input.json output.csv"

	cmd.RunE = func(cmd *cobra.Command, args []string) (err error) {
		defer xerror.RespErr(&err)

		_in := "input.json"
		_out := "output.csv"

		switch len(args) {
		case 1:
			_in = args[0]
		case 2:
			_in = args[0]
			_out = args[1]
		}

		var _inData []byte

		if IsURL(_in) {
			resp := xerror.PanicErr(http.Get(_in)).(*http.Response)
			_inData = xerror.PanicBytes(ioutil.ReadAll(resp.Body))
		} else {
			_inData = xerror.PanicBytes(ioutil.ReadFile(_in))
		}

		_head := map[string]bool{}
		var dt []map[string]gjson.Result
		var _data gjson.Result

		_data = gjson.ParseBytes(_inData)
		if expr != "" {
			_data = _data.Get(expr)
		}

		for _, d := range _data.Array() {
			_d := d.Map()
			dt = append(dt, _d)

			for k := range _d {
				_head[k] = true
			}
		}

		_wfs := xerror.PanicErr(os.OpenFile(_out, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)).(*os.File)
		defer _wfs.Close()
		_wfs.Seek(0, io.SeekEnd)

		w := csv.NewWriter(_wfs)
		w.Comma = ','
		w.UseCRLF = true

		var _head1 = MapKeys(_head).([]string)
		xerror.Panic(w.Write(_head1))

		for i := 0; i < len(dt); i++ {
			var _dt1 []string
			for j := 0; j < len(_head1); j++ {
				_dt1 = append(_dt1, dt[i][_head1[j]].String())
			}
			xerror.Panic(w.Write(_dt1))
		}

		w.Flush()
		return
	}
})

Execute exec

Functions

func IsURL

func IsURL(u string) bool

IsURL 检查是否为url地址

func MapKeys

func MapKeys(data interface{}) interface{}

MapKeys 获取map的keys

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL