gpanda
gpanda

Reputation: 875

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

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.

Upvotes: 2

Views: 930

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79784

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.

Upvotes: 4

Related Questions