douqu8828 2015-01-30 17:57
浏览 81

Go Lang返回JSON

Still pretty new with Go. I'm trying to get go to essentially print a struct with the keys and values as close to json as possible.

The way I'm currently doing this is having GO on it's own server and whenever a get request is made, it returns the JSON. I would like to have GO as an executable on my primary Rails server and just return the JSON with something like Println (or whatever would make it stay in struct form). The problem is when I try to go this route, the keys from the struct aren't printed with it and I would basically have to add the keys as part of the return string.

Is there a simple way to do this with keeping the correct keys and values (and their types, so if the value is an array, keep the array)

  • 写回答

1条回答 默认 最新

  • dongsaoshuo4326 2015-01-30 18:12
    关注

    Printing a struct as JSON to STDOUT is fairly straight forward in Go:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        foo := struct {
            Hello string
            JSON  string
        }{
            Hello: "world",
            JSON:  "stuff",
        }
    
        fmt.Printf("foo struct : %+v
    ", foo)
    
        if err := json.NewEncoder(os.Stdout).Encode(foo); err != nil {
            log.Fatal(err)
        }
    
    }
    

    http://play.golang.org/p/wqqGJ1V_Zg

    That program will output the following:

    foo struct : {Hello:world JSON:stuff}
    {"Hello":"world","JSON":"stuff"}
    

    From your question I really didn't understand what you meant. In any case, if you wanted to print the struct as JSON or if you just wanted to print the struct as close to JSON as possible your answer is there.

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能