...

Source file src/github.com/pelletier/go-toml/v2/cmd/tomljson/main.go

Documentation: github.com/pelletier/go-toml/v2/cmd/tomljson

     1  // Package tomljson is a program that converts TOML to JSON.
     2  //
     3  // # Usage
     4  //
     5  // Reading from stdin:
     6  //
     7  //	cat file.toml | tomljson > file.json
     8  //
     9  // Reading from a file:
    10  //
    11  //	tomljson file.toml > file.json
    12  //
    13  // # Installation
    14  //
    15  // Using Go:
    16  //
    17  //	go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest
    18  package main
    19  
    20  import (
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  
    26  	"github.com/pelletier/go-toml/v2"
    27  	"github.com/pelletier/go-toml/v2/internal/cli"
    28  )
    29  
    30  const usage = `tomljson can be used in two ways:
    31  Reading from stdin:
    32    cat file.toml | tomljson > file.json
    33  
    34  Reading from a file:
    35    tomljson file.toml > file.json
    36  `
    37  
    38  func main() {
    39  	p := cli.Program{
    40  		Usage: usage,
    41  		Fn:    convert,
    42  	}
    43  	p.Execute()
    44  }
    45  
    46  func convert(r io.Reader, w io.Writer) error {
    47  	var v interface{}
    48  
    49  	d := toml.NewDecoder(r)
    50  	err := d.Decode(&v)
    51  	if err != nil {
    52  		var derr *toml.DecodeError
    53  		if errors.As(err, &derr) {
    54  			row, col := derr.Position()
    55  			return fmt.Errorf("%s\nerror occurred at row %d column %d", derr.String(), row, col)
    56  		}
    57  		return err
    58  	}
    59  
    60  	e := json.NewEncoder(w)
    61  	e.SetIndent("", "  ")
    62  	return e.Encode(v)
    63  }
    64  

View as plain text