I have toml file and that needs to be converted to Json and vice versa and in golang packages it has just command tools rather than functions. It would be great if anyone has precise idea about how to convert toml to json and vice versa in Go language
Asked
Active
Viewed 709 times
1 Answers
1
I would just use some popular toml library to parse toml to a struct and then use the standard library to marhshal it to JSON.
The below code makes use of https://github.com/BurntSushi/toml.
Note, no error handling for brevity.
type Config struct {
Age int `json:"age,omitempty"`
Cats []string `json:"cats,omitempty"`
Pi float64 `json:"pi,omitempty"`
Perfection []int `json:"perfection,omitempty"`
DOB time.Time `json:"dob,omitempty"`
}
var tomlData = `
Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z`
func main() {
var conf Config
toml.Decode(tomlData, &conf)
j, _ := json.MarshalIndent(conf, "", " ")
fmt.Println(string(j))
}
Output:
{
"age": 25,
"cats": [
"Cauchy",
"Plato"
],
"pi": 3.14,
"perfection": [
6,
28,
496,
8128
],
"dob": "1987-07-05T05:45:00Z"
}

The Fool
- 16,715
- 5
- 52
- 86
-
Is there any way i can load file and parse toml and convert to json – Srinivas Gowda Jan 19 '22 at 11:09
-
@SrinivasGowda, of course you can read some file content with go. You should be able to figure out how to do it by consulting the go docs. Its pretty straight forward. – The Fool Jan 19 '22 at 11:40
-
I'm creating a Window Installer where i can deploy my agent(Golang script which contains data) to other window servers Is It better to go with WiX toolkit or is there already installer where i can deploy my agent into other window Servers – Srinivas Gowda Feb 01 '22 at 10:41