duandao6414 2018-11-30 13:23
浏览 199
已采纳

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

I need to create a JSON array using map.

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

}

My current output:

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]

I need a JSON output like below:

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

I know basics of using map its a dictionary used for key:value pairs.How can I achieve JSON output using map.

  • 写回答

2条回答 默认 最新

  • dpy15285 2018-11-30 14:06
    关注

    To create array of JSON through map, you need to create one map as a slice and another one just single map and then assign value one by one in single map then append this into slice of map, like follow the below code:

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

    Also you can test over here

    it prints JSON as:

    [{"id":"1","name":"A"},
    {"id":"2","name":"B"},
    {"id":"3","name":"C"},
    {"id":"4","name":"D"},
    {"id":"5","name":"E"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 nslt的可用模型,或者其他可以进行推理的现有模型
  • ¥15 arduino上连sim900a实现连接mqtt服务器
  • ¥15 vncviewer7.0安装后如何正确注册License许可证,激活使用
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并2
  • ¥66 关于人体营养与饮食规划的线性规划模型
  • ¥15 基于深度学习的快递面单识别系统
  • ¥15 Multisim仿真设计地铁到站提醒电路
  • ¥15 怎么用一个500W电源给5台60W的电脑供电
  • ¥15 请推荐一个轻量级规则引擎,配合流程引擎使用,规则引擎负责判断出符合规则的流程引擎模板id
  • ¥15 Excel表只有年月怎么计算年龄