read a json file in go

To read a JSON file in Go, you can use the encoding/json package to unmarshal the file's contents into a struct. Here's an example:

main.go
package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    // Read the JSON file
    file, err := os.Open("file.json")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // Unmarshal the JSON data into a struct
    var person Person
    err = json.NewDecoder(file).Decode(&person)
    if err != nil {
        panic(err)
    }

    // Print the person's name and age
    fmt.Printf("Name: %s\n", person.Name)
    fmt.Printf("Age: %d\n", person.Age)
}
579 chars
33 lines

In this example, we define a Person struct with Name and Age fields. We then read the contents of the file.json file using the os.Open function, and unmarshal the JSON data into a Person struct using json.NewDecoder(file).Decode(&person).

We can then print out the person's name and age using fmt.Printf.

related categories

gistlibby LogSnag