Golang JSON to Slice of Maps of Maps themselves Containing Slices (without Types)

Viewed 828

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 Answers
Related