将JSON解码为map[string]map[string]string

huangapple go评论91阅读模式
英文:

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

问题

我有一个map[string]map[string]string,我想将其转换为JSON并写入文件,然后能够从文件中读取数据。

我已经成功地使用以下代码将数据写入文件:

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的类型是map[string]map[string]string
    return encoder.Encode(l.data)
}

但是我在将JSON加载回map时遇到了问题。我尝试了以下代码:

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

当加载内容为{"bar":{"hello":"world"},"foo":{"bar":"new","baz":"extra"}}的JSON文件后,l.data的内容只是map[]。我该如何成功地将JSON解码到l.data中?

英文:

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

得分: 3

如果您使用json.Unmarshal(),您可以传递一个数据结构来填充它。以下是下面代码的链接,在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)
    // 打印出结构
    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")
}
英文:

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 <a href="http://play.golang.org/p/flOcMhYt2H">playground</a>.

package main

import (
	&quot;fmt&quot;
	&quot;encoding/json&quot;
	)

func main() {
	src_json := []byte(`{&quot;bar&quot;:{&quot;hello&quot;:&quot;world&quot;},&quot;foo&quot;:{&quot;bar&quot;:&quot;new&quot;,&quot;baz&quot;:&quot;extra&quot;}}`)
	d := map[string]map[string]string{}
	_ = json.Unmarshal(src_json, &amp;d)
    // Print out structure
	for k, v := range d {
		fmt.Printf(&quot;%s\n&quot;, k)
		for k2, v2 := range v {
			fmt.Printf(&quot;\t%s: %s\n&quot;, k2, v2)
		}
	}
	fmt.Println(&quot;Hello, playground&quot;)
}

huangapple
  • 本文由 发表于 2013年5月27日 07:45:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/16764719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定