简体   繁体   English

如何将 json 解组为 Go map 结构?

[英]How to unmarshall json into Go map of structs?

I'm new to Go and I'm having a hard time dealing with json files.我是 Go 的新手,我很难处理 json 文件。 I have JSON data which I want to convert into a map of type map[string]*SomeStruct我有 JSON 数据,我想将其转换为 map[string]*SomeStruct 类型的 map

Sample JSON:样品 JSON:

{
        "Component": 
        {
                "fieldName": "component.name", 
                "fieldType": "STR" 
        },
        "Collection": {     
                "fieldName": "collection", 
                "fieldType": "INT"
        },
        "OldgenUse" : {     
                "fieldName" : "oldgen.use",         
                "fieldType": "INT"      
        },
    
}

I want to read the JSON and build a map like this:我想阅读 JSON 并像这样构建 map:

    expcMetadata := map[string]*FieldMap{
            "Component":    {FieldName: "component.name", FieldType: "STR"},
            "Collection":   {FieldName: "collection", FieldType: "INT"},
            "OldGenUse":    {FieldName: "oldgen.use", FieldType: "INT"},
}

I am able to unmarshall into a map[string]interface{}.我能够解组为 map[string]interface{}。 How can unmarshall into a map[string]*FieldMap如何解组为 map[string]*FieldMap

My code which gives me an empty map:我的代码给了我一个空的 map:

type FieldMap struct {
    FieldName string `json:"fieldName"`
    FieldType        string `json:"fieldType"`
}

type JSONType struct {
    FieldSet map[string]FieldMap `json:"fields"`
}
func main() {

    jsonFile, er := os.Open("fields.json")
    if er != nil {
        fmt.Println(er)
    }
    fmt.Println("Successfully Opened users.json")
    defer jsonFile.Close()

    byteValue, _ := ioutil.ReadAll(jsonFile)

    // var m map[string]interface{}
    var m JSONType
    err := json.Unmarshal(byteValue, &m)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(m)

} 

I would really appreciate if someone could help me out with this.如果有人可以帮助我解决这个问题,我将不胜感激。

Your input JSON is an object, so marshal that into a map directly .您的输入 JSON 是 object,因此直接将其编组为 map。 The wrapper JSONType is unnecessary.包装器JSONType是不必要的。

var m map[string]FieldMap
err := json.Unmarshal(byteValue, &m)
if err != nil {
    log.Fatal(err)
}

See a working example on the Go Playground , output is:请参阅Go Playground上的工作示例,output 是:

map[Collection:{collection INT} Component:{component.name STR} OldgenUse:{oldgen.use INT}]

For your struct JSONType in JSON need a fields node.对于JSONType中的结构 JSONType 需要一个fields节点。 Rather you can use map when unmarshaling.相反,您可以在解组时使用 map。

m := make(map[string]FieldMap)
err := json.Unmarshal(byteValue, &m)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM