2

I have a map[string]map[string]string that I'd like to be able to convert to JSON and write to a file, and be able to read the data back in from the file.

I've been able to successfully write to the file using the following:

func (l *Locker) Save(filename string) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    encoder := json.NewEncoder(file)
    // l.data is of type map[string]map[string]string
    return encoder.Encode(l.data)
}

I'm having trouble loading the JSON back into the map. I've tried the following:

func (l *Locker) Load(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    decoder := json.NewDecoder(file)
    return decoder.Decode(l.data)
}

loading a JSON file with contents {"bar":{"hello":"world"},"foo":{"bar":"new","baz":"extra"}}, and after the above the contents of l.data is just map[]. How can I successfully decode this JSON into l.data?

1 Answer 1

3

If you use json.Unmarshal() instead you can pass it a data structure to populate. Here's a link to the code below, in the playground.

package main

import (
    "fmt"
    "encoding/json"
    )

func main() {
    src_json := []byte(`{"bar":{"hello":"world"},"foo":{"bar":"new","baz":"extra"}}`)
    d := map[string]map[string]string{}
    _ = json.Unmarshal(src_json, &d)
    // Print out structure
    for k, v := range d {
        fmt.Printf("%s\n", k)
        for k2, v2 := range v {
            fmt.Printf("\t%s: %s\n", k2, v2)
        }
    }
    fmt.Println("Hello, playground")
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! After working through your example and taking a cloer look at my code, I realized I needed to be passing a pointer to json.Decode but wasn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.