猿问

如何使用 Go map 创建对象的 JSON 数组?

我需要使用地图创建一个 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 的基础知识它是用于键:值对的字典。如何使用 map 实现 JSON 输出。


沧海一幻觉
浏览 117回答 2
2回答

胡子哥哥

要创建 through map 数组JSON,您需要创建一个map作为slice单个 map 而另一个只是单个 map,然后在单个 map 中一个一个地赋值,然后将其附加到 slice of map 中,如下面的代码所示:package mainimport (    "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为:[{"id":"1","name":"A"},{"id":"2","name":"B"},{"id":"3","name":"C"},{"id":"4","name":"D"},{"id":"5","name":"E"}]

收到一只叮咚

对我来说,这更像是一组对象。您可以像这样获得所需的输出: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"}]
随时随地看视频慕课网APP

相关分类

Go
我要回答