This module converts a json blob to go code. The generated code includes both a struct definition and an instance for the input json.
Reading from stdin is supported, as well as reading from input files, making it suitable for use with go generate
.
Try the following example to generate code from stdin:
cat <<EOF | go run .
{
"name": "bob",
"age": 28
}
EOF
The generated go source will be written to the console, including both the struct definition and an instance.
Be sure to check out the example app
To use this module with go generate
, use a directive like the following in your go source:
//go:generate go run github.com/christopherriley/json2go -in config.json -out config.go -struct Config -var config
Create a simple json file to start with, for example
config.json
{
"name": "bob",
"age": 28
}
Create a go program that will consume the json file. include the go generate
directive.
main.go
package main
import "fmt"
//go:generate go run github.com/christopherriley/json2go -in config.json -out config.go -struct Config -var config
func main() {
// note the instance variable name matches the -var flag to the generate directive, above
fmt.Println("name: ", config.name)
fmt.Println("age: ", config.age)
}
In order for the app to run, the go code will need to be generated from the json
go generate
You can examine the generated source
cat config.go
// this file was generated from config.json
// do not modify
package main
type Config struct {
age int
name string
}
var config Config = Config{
age: 28,
name: "bob",
}
go run main.go config.go
You should see the following output:
name: bob
age: 28
json/javascript has support for mixed arrays. go can achieve the same thing using []any
, but defeats the purpose of this project. therefore json arrays with mixed types are not supported.