douli0531 2015-01-06 13:06
浏览 179
已采纳

我可以将动态创建的json格式化为开发快递图表所需的格式吗

I have written a go program for giving json as a response to the httpRequest,but i am able to create json in this format only :

{
  "Country": [
        "abc",
        "def",

    ],
    "Population": [
        "8388344",
        "343",

    ]
}

The content types are dynamically defined using map[string]string.Can someone please help me out to give the json in the below format:

[
    {
       "Country" :"abc",
       "Population" :"8388344"
    },
    {
        "Country" : "def",
        "Population" :"343"
    },
    ...
]

Please help me out..

  • 写回答

1条回答

  • douci1615 2015-01-06 13:20
    关注

    You just need to make a slice of structs. Adapted from the doc example:

    type Tuple struct {
        Country    string
        Population string
    }
    tuples := []Tuple{
        {Country: "abc", Population: "1234"},
        {Country: "def", Population: "567"},
    }
    
    b, err := json.Marshal(tuples)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
    

    This produces:

    [
        {"Country":"abc","Population":"1234"},
        {"Country":"def","Population":"567"}
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名