create a json file in go

Here's an example Go code to create a JSON file:

main.go
package main

import (
    "encoding/json"
    "io/ioutil"
)

type Person struct {
    FirstName string `json:"firstName"`
    LastName  string `json:"lastName"`
    Age       int    `json:"age"`
}

func main() {
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    jsonPerson, _ := json.MarshalIndent(person, "", "  ")

    err := ioutil.WriteFile("person.json", jsonPerson, 0644)
    if err != nil {
        panic(err)
    }
}
485 chars
28 lines

In this example, we define a Person struct with json tags to define the property names in the resulting JSON file. We then create a new Person instance and marshal it into a JSON byte array using json.MarshalIndent. Finally, we use ioutil.WriteFile to write the byte array to a file called person.json. The file will be created if it does not exist, or overwritten if it does.

gistlibby LogSnag