mySitio / cmd / web / helpers.go
helpers.go
Raw
package main

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

// opens json file and returns parsed values in accordance to given elements slice as a slice of strings
func openStoreJson(filename string, elements *[]string) ([]string, error) {
	//open json file and defer closing
	jsonFile, err := os.Open("content_data/" + filename)
	if err != nil {
		return nil, err
	}
	defer jsonFile.Close()

	retSlice := []string{} //empty slice of strings to return

	//read json file as bytes
	byteResult, err := io.ReadAll(jsonFile)
	if err != nil {
		return nil, err
	}

	//make bytes into a readable format by go
	v := make(map[string]interface{})
	json.Unmarshal([]byte(byteResult), &v)

	//iterate over given elements and append them to slice
	for _, section := range *elements {
		retSlice = append(retSlice, fmt.Sprint(v[section])) //uses string representation and appends it to the retsice
	}

	return retSlice, nil //pointer to slice returned for memory and performance boost
}