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

时间:2017-08-16 17:04:48

标签: json go hashmap slice

我的SELECT issuer_id, COUNT(*) FROM TABLE(MULTISET( SELECT acct.fund_acct_nbr, acct.bin, prod.issuer_id, COUNT(*) FROM fund_acct AS acct JOIN products AS prod ON acct.cusip = prod.cusip WHERE prod.issuer_id = 'xxxx' AND SUBSTR(acct.bin, 1, 1) = 'x' GROUP BY acct.fund_acct_nbr, acct.bin, prod.issuer_id )) GROUP BY issuer_id; 格式如下:

config.json

如果可能的话,我想将其转换为一张地图片,其中每张地图本身就是一个“关键字”,而“值”是一个切片。

我可以手动完成此操作:

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

相反,我想在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) } 的内容上调用json.Unmarshal来将json解析为完全相同的结构。

到目前为止我尝试过:

config.json

这会产生错误:

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)
    }

非常感谢任何帮助,欢迎澄清问题。感谢。

1 个答案:

答案 0 :(得分:4)

您的JSON输入和您的"手册"示例是使用切片的贴图,而不是切片的贴图。将您的目标类型更改为map[string][]string,您应该很高兴:

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)
}

产生以下输出:

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

Playground link