find the name of a json file in go

To find the name of a JSON file in Go, you can use the ioutil package to read the contents of a directory and then loop through each file to check if it has a .json extension. Once you find the file with the JSON data, you can return its name as a string.

Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "io/ioutil"
    "path/filepath"
)

func main() {
    dirPath := "/path/to/json/files/directory"
    files, err := ioutil.ReadDir(dirPath)
    if err != nil {
        panic(err)
    }

    for _, file := range files {
        if filepath.Ext(file.Name()) == ".json" {
            fmt.Println("Found JSON file:", file.Name())
            break
        }
    }
}
397 chars
23 lines

In this code, we first set the dirPath variable to the path of the directory containing our JSON files. We then use ioutil.ReadDir to get a slice of os.FileInfo describing each file in the directory.

We then loop through each file using a for ... range loop and check if the file has a .json extension using filepath.Ext. If we find a file with a .json extension, we print its name using fmt.Println and break out of the loop using break.

gistlibby LogSnag