Using json decode

Hello, another newbie question here. I have the following code:

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

// Config struct is read from ~/.golog config file
type Config struct {
	UseShortMessages bool
}

func main() {
	file, _ := os.Open("~/.golog")
	decoder := json.NewDecoder(file)
	config := Config{}
	err := decoder.Decode(config)
	if err != nil {
		fmt.Println("error:", err)
	}
	if config.UseShortMessages {
		fmt.Println("Use short messages")
	} else {
		fmt.Println("Use long messages")
	}
}

The JSON file consists of:

{
    "UseShortMessages": false
}

The decoder.Decode function is always bombing out with an error: invalid argument error.
What am I missing here?

Thanks in advance,
Carl

Try decoder.Decode(&config).

Also, please check the error from os.Open.

Sorry that line was previously decoder.Decode(&config) . I copy and pasted my message after changing the code.
decoder.Decode(&config) gives the same error.

However, I’ve checked the error from the os.Open line and that’s telling me that there’s no such file or directory. But I’ve literally just created the file. Does os.Open not work with the ~ notation for the user’s home folder?

~ notation is a feature of the shell (i.e., bash) and is not supported by os.Open.

1 Like

That makes sense.

I’ve rewritten the code as:

package main

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

// Config struct is read from ~/.golog config file
type Config struct {
	UseShortMessages bool
}

func main() {
	usr, err := user.Current()
	if err != nil {
		reportError(err)
	}
	configFile := path.Join(usr.HomeDir, ".golog")
	file, err := os.Open(configFile)
	if err != nil {
		reportError(err)
	}
	decoder := json.NewDecoder(file)
	config := Config{}
	err = decoder.Decode(&config)
	if err != nil {
		reportError(err)
	}
	if config.UseShortMessages {
		fmt.Println("Use short messages")
	} else {
		fmt.Println("Use long messages")
	}
}

func reportError(err error) {
	fmt.Println("error:", err)
}

It seems to work nicely now. Thanks for the help Nathan.

1 Like

Try more elegant

if err := json.NewDecoder(file).Decode(&config); err != nil {
	log.Println(err.Error())
}

:slight_smile:

Thanks, George. I did toy with trying that but I couldn’t seem to use that approach for the file, err := os.Open(configFile)line, I guess, because of the double assignment of variables. For consistency, I chose not to have a mix of styles.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.