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"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?