duanliao5995 2018-04-26 14:53
浏览 105
已采纳

正确从Golang输出JSON块

I have search for a solution for this problem. It is actually from a sql database, but this illustrates the problem as well:

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    m := map[string]string{
      "USER_ID":"JD", 
      "USER_NAME":"John Doe",
    }

    json, _ := json.Marshal(m)
    for i := 0; i < 4; i++ {
       fmt.Println(string(json))
    }

}

https://play.golang.org/p/7DQPiB0aWAK

Each row is correct, but it each row is not separated by comma and surrounded by square brackets.

{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}

The desired output is this:

[{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"}]

Is this possible using map[string]string or interface?

  • 写回答

1条回答 默认 最新

  • dongweizhen2009 2018-04-26 16:14
    关注

    Is this possible using map[string]string or interface?

    The answer is simple - You can use a slice whenever you want to produce a list output in JSON.

    Here is your example with the desired output (playground) :

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        // define a slice of maps
        var mySlice []map[string]string
    
        // define a map
        m := map[string]string{
          "USER_ID":"JD", 
          "USER_NAME":"John Doe",
        }
    
        // add the map 4 times to the slice
        for i := 0; i < 4; i++ {
            mySlice = append(mySlice, m)
        }
    
        // print the slice
        json, _ := json.Marshal(mySlice)
        fmt.Println(string(json))
    }
    // Output: [{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站