douman9420
2017-08-16 17:04
浏览 97

Golang JSON到包含切片(无类型)的地图切片的切片

I have a config.json with the following format:

{
    "recordType1": [
        "field1", "field2", "field3", "field4", "field5"
    ],
    "recordType2": [
        "field1", "field2", "field3", "field4", "field5", "field6", "field7"
    ]
}

If possible, I'd like to convert this to a slice of maps, where each map is itself is a single 'key', and the 'value' is a slice.

I can accomplish this manually like:

package main

import ("fmt")

func main() {
        m := make(map[string][]string, 0)
        m2 := make(map[string][]string, 0)
        sliceOfMaps := make([]map[string][]string, 0)

        m["recordType1"] = []string{"field1", "field2", "field3"}
        m2["recordType2"] = []string{"field1", "field2", "field3", "field4", "field5"}
        sliceOfMaps = append(sliceOfMaps, m, m2)

        fmt.Println(m)
        fmt.Println(m2)
        fmt.Println(sliceOfMaps)
}

Instead, I'd like to invoke json.Unmarshal on the contents of config.json to parse that json into the very same structure.

What I've tried so far:

package main

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
)


    func main() {
        file, err := ioutil.ReadFile("config/config.json")
        if err != nil {
                log.Fatal("Err Reading File:", err)
        }

        var sliceOfMaps []map[string][]string
        sliceOfMaps = make([]map[string][]string, 0)

        err = json.Unmarshal(file, &sliceOfMaps)
        if err != nil {
                log.Fatal("Err Parsing JSON", err)
        }

        fmt.Println(sliceOfMaps)
    }

This produces error:

Err Parsing JSONjson: cannot unmarshal object into Go value of type []map[string][]string

Any assistance is greatly appreciated, clarifying questions welcome. Thanks.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujia2463 2017-08-16 17:10
    已采纳

    Both your JSON input, and your "manual" example are using maps of slices, not slices of maps. Change your target type to map[string][]string and you should be good to go:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    var file = []byte(`{
        "recordType1": [
            "field1", "field2", "field3", "field4", "field5"
        ],
        "recordType2": [
            "field1", "field2", "field3", "field4", "field5", "field6", "field7"
        ]
    }`)
    
    func main() {
        output := map[string][]string{}
        if err := json.Unmarshal(file, &output); err != nil {
            panic(err)
        }
        fmt.Println(output)
    }
    

    Produces the following output:

    map[recordType1:[field1 field2 field3 field4 field5] recordType2:[field1 field2 field3 field4 field5 field6 field7]]
    

    Playground link.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题