如何使用golang映射创建JSON数组?

时间:2018-11-30 13:23:56

标签: dictionary go

我需要使用map创建一个JSON数组。

package main
import "fmt"
func main(){
    id := [5]string{"1","2","3","4","5"}
    name := [5]string{"A","B","C","D","E"}
    parseData := make(map[string]string)
    for counter,_ := range id {
        parseData["id"] = id[counter]
        parseData["name"] = name[counter]
        fmt.Println(parseData)
    }

}

我当前的输出:

map[id:1 name:A]
map[id:2 name:B]
map[id:3 name:C]
map[id:4 name:D]
map[id:5 name:E]

我需要如下所示的JSON输出:

[{id:1, name:A},
{id:2, name:B},
{id:3, name:C},
{id:4, name:D},
{id:5, name:E}]

我了解使用map的基础知识,它是用于key:value对的字典。如何使用map实现JSON输出。

2 个答案:

答案 0 :(得分:6)

要通过地图创建JSON的数组,您需要将一个map创建为slice,将另一个package main import ( "fmt" "encoding/json" ) func main(){ id := [5]string{"1","2","3","4","5"} name := [5]string{"A","B","C","D","E"} parseData := make([]map[string]interface{}, 0, 0) for counter,_ := range id { var singleMap = make(map[string]interface{}) singleMap["id"] = id[counter] singleMap["name"] = name[counter] parseData = append(parseData, singleMap) } b, _:= json.Marshal(parseData) fmt.Println(string(b)) } 创建为单个地图,然后在单个地图中一个接一个地分配值,然后追加将其放入地图切片中,例如遵循以下代码:

JSON

您还可以在here上进行测试

它将[{"id":"1","name":"A"}, {"id":"2","name":"B"}, {"id":"3","name":"C"}, {"id":"4","name":"D"}, {"id":"5","name":"E"}] 打印为:

{{1}}

答案 1 :(得分:2)

对我来说,这更像是一个对象数组。您可以这样获得所需的输出:

type data struct {
    Id string
    Name string
}

func main(){
    id := [5]string{"1","2","3","4","5"}
    name := [5]string{"A","B","C","D","E"}
    var parsedData []data

    for counter := range id {
        parsedData = append(parsedData, data{Name: name[counter], Id: id[counter]})
    }

    bytes, _ := json.Marshal(parsedData)
    fmt.Print(string(bytes))
}

输出应如下所示:

[
 {"Id":"1","Name":"A"},
 {"Id":"2","Name":"B"},
 {"Id":"3","Name":"C"},
 {"Id":"4","Name":"D"},
 {"Id":"5","Name":"E"}
]