英文:
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 (
"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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论