...

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

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

     1  // Package jsontoml is a program that converts JSON to TOML.
     2  //
     3  // # Usage
     4  //
     5  // Reading from stdin:
     6  //
     7  //	cat file.json | jsontoml > file.toml
     8  //
     9  // Reading from a file:
    10  //
    11  //	jsontoml file.json > file.toml
    12  //
    13  // # Installation
    14  //
    15  // Using Go:
    16  //
    17  //	go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest
    18  package main
    19  
    20  import (
    21  	"encoding/json"
    22  	"flag"
    23  	"io"
    24  
    25  	"github.com/pelletier/go-toml/v2"
    26  	"github.com/pelletier/go-toml/v2/internal/cli"
    27  )
    28  
    29  const usage = `jsontoml can be used in two ways:
    30  Reading from stdin:
    31    cat file.json | jsontoml > file.toml
    32  
    33  Reading from a file:
    34    jsontoml file.json > file.toml
    35  `
    36  
    37  var useJsonNumber bool
    38  
    39  func main() {
    40  	flag.BoolVar(&useJsonNumber, "use-json-number", false, "unmarshal numbers into `json.Number` type instead of as `float64`")
    41  
    42  	p := cli.Program{
    43  		Usage: usage,
    44  		Fn:    convert,
    45  	}
    46  	p.Execute()
    47  }
    48  
    49  func convert(r io.Reader, w io.Writer) error {
    50  	var v interface{}
    51  
    52  	d := json.NewDecoder(r)
    53  	e := toml.NewEncoder(w)
    54  
    55  	if useJsonNumber {
    56  		d.UseNumber()
    57  		e.SetMarshalJsonNumbers(true)
    58  	}
    59  
    60  	err := d.Decode(&v)
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	return e.Encode(v)
    66  }
    67  

View as plain text