0
我很难搞清楚如何将JSON文件的“小节”加载到地图元素中。背景:我想解组一个有些复杂的配置文件,它具有严格的结构,所以我认为最好是解组成一个“静态”结构而不是一个接口。解组成JSON到地图中去
这里例如一个简单的JSON文件:
{
"set1": {
"a":"11",
"b":"22",
"c":"33"
}
}
此代码:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type JSONType struct {
FirstSet ValsType `json:"set1"`
}
type ValsType struct {
A string `json:"a"`
B string `json:"b"`
C string `json:"c"`
}
func main() {
file, e := ioutil.ReadFile("./test1.json")
if e != nil {
fmt.Println("file error")
os.Exit(1)
}
var s JSONType
json.Unmarshal([]byte(file), &s)
fmt.Printf("\nJSON: %+v\n", s)
}
但这并不:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type JSONType struct {
FirstSet ValsType `json:"set1"`
}
type ValsType struct {
Vals map[string]string
}
func main() {
file, e := ioutil.ReadFile("./test1.json")
if e != nil {
fmt.Println("file error")
os.Exit(1)
}
var s JSONType
s.FirstSet.Vals = map[string]string{}
json.Unmarshal([]byte(file), &s)
fmt.Printf("\nJSON: %+v\n", s)
}
的瓦尔斯地图不是装。我究竟做错了什么?谢谢你的帮助!
这里有一个更好的例子:
{
"set1": {
"a": {
"x": "11",
"y": "22",
"z": "33"
},
"b": {
"x": "211",
"y": "222",
"z": "233"
},
"c": {
"x": "311",
"y": "322",
"z": "333"
},
}
}
代码:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type JSONType struct {
FirstSet map[string]ValsType `json:"set1"`
}
type ValsType struct {
X string `json:"x"`
Y string `json:"y"`
Z string `json:"z"`
}
func main() {
file, e := ioutil.ReadFile("./test1.json")
if e != nil {
fmt.Println("file error")
os.Exit(1)
}
var s JSONType
json.Unmarshal([]byte(file), &s)
fmt.Printf("\nJSON: %+v\n", s)
}
感谢您的快速回复。这完全有道理......不幸的是我简化了我的例子。的数据是更以下形式:'{ “SET1”:{ “一”:{ \t “×”: “11” 时, \t “Y”: “22”, \t “Z”:“33 “ \t}, ”b“:{ \t ”ד: ”211“, \t ”Y“: ”222“, \t ”Z“: ”233“ \t}, ”C“:{ \t“x”:“311”, \t“y”:“322”, \t“z”:“333” \t}, } }',我想创建一个结构图 - 即map [string] StuctXType。 –
@JamesHaskell很酷,我为你编辑了更多关于模型的文章:D – evanmcdonnal
再次感谢 - 我真的很感谢你的帮助。上面列出的路径是我从昨天开始一直在尝试的,但它不适用于我......不知道为什么,如果我有我错过了或错过了一个错字。我将我的修改过的代码发布为我的原始编辑...我得到的结果是:'JSON:{FirstSet:map []}'。任何额外的想法?或者你能为我发布一个完整的工作示例吗?非常感谢。我很开心学习去... –