mfonda
mfonda

Reputation: 8003

Decode JSON to map[string]map[string]string

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?

Upvotes: 2

Views: 680

Answers (1)

Daniel
Daniel

Reputation: 38849

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")
}

Upvotes: 3

Related Questions